1. 程式人生 > >使用ajaxSubmit非同步上傳圖片並展示

使用ajaxSubmit非同步上傳圖片並展示

頁面在選擇圖片完成後將圖片上傳到圖片伺服器,並在頁面顯示圖片,然後將上傳圖片的路徑載入到隱藏域中,提交表單時將路徑儲存到資料庫。
頁面程式碼:

<script>
function submitUpload(){
    var option = {
            url:"${path}/upload/uploadPic.do",//如果不指定url那麼就使用使用提交表單的url,如果指定就使用當前的url
            dataType:"text",
            success:function(responseText){
                var
jsonObj = $.parseJSON(responseText); $("#imgsImgSrc").attr("src", jsonObj.realPath); $("#imgs").val(jsonObj.relativePath); }, error:function(){ alert("系統錯誤"); } }; $("#form").ajaxSubmit(option); }
</script
>
<form id="form" name="form" action="${path }/add.do" method="post" enctype="multipart/form-data">
    <input type='file' size='27' id='imgsFile' name='imgsFile' class="file" onchange='submitUpload()' /><span id="submitImgTip" class="pos">請上傳圖片寬為120px,高為50px,大小不超過100K。</span>
    <input
type='hidden' id='imgs' name='imgs' value='' reg2="^.+$" tip="親!您忘記上傳圖片了。" />
<span></span> </form>

java程式碼:

    @RequestMapping("/uploadPic.do")
    public void uploadPic(HttpServletRequest request, Writer out) throws IOException{
        //把request轉換成複雜request
        MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
        //獲得檔案,此方法實用性強,可以多檔案複用。
        Map<String, MultipartFile> map = mr.getFileMap();
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        String fileInputName = it.next();
        MultipartFile mf = map.get(fileInputName);
        //獲得檔案的位元組陣列
        byte [] bs = mf.getBytes();
        String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        Random random = new Random();
        for(int i = 0; i < 3; i++){
            fileName = fileName + random.nextInt(10);
        }

        String oriFileName = mf.getOriginalFilename();
        //獲得檔案的字尾
        String suffix = oriFileName.substring(oriFileName.lastIndexOf("."));
        //獲得上傳檔案的絕對路徑
        String realPath = ECPSUtils.readProp("file_path")+"/upload/"+fileName+suffix;
        //獲得相對路徑
        String relativePath = "/upload/"+fileName+suffix;
        //建立jersy的客戶端
        Client client = Client.create();
        //建立web資源物件
        WebResource wr = client.resource(realPath);
        //上傳
        wr.put(bs);
        JSONObject jo = new JSONObject();
        jo.accumulate("realPath", realPath);
        jo.accumulate("relativePath", relativePath);
        String result = jo.toString();
        out.write(result);
    }

謝謝!