1. 程式人生 > >Spring MVC利用Ajax上傳圖片

Spring MVC利用Ajax上傳圖片

html

<input type="file" onchange="imageUpload(this)" class="form-control" placeholder="點選按鈕選擇圖片"id="pictureUpload">

Ajax

function imageUpload(obj) {
        //判斷圖片格式
        var fileName=obj.value;
        var suffixIndex=fileName.lastIndexOf(".");
        var suffix=fileName.substring(suffixIndex+1).toUpperCase();
        if(suffix!="BMP"&&suffix!="JPG"&&suffix!="JPEG"&&suffix!="PNG"&&suffix!="GIF"){
            layer.msg( "請上傳圖片(格式BMP、JPG、JPEG、PNG、GIF等)!");
            var file = $("#pictureUpload");
            file.after(file.clone().val(""));
            file.remove();
            return;
        }

        var formData = new FormData();
        formData.append('file', $('#pictureUpload')[0].files[0]);  //新增圖片資訊的引數
        $.ajax({
            type: "POST",
            url: "/fileUploadPage.do",
            data:formData,
            cache: false, //上傳檔案不需要快取
            processData: false,// 告訴jQuery不要去處理髮送的資料
            contentType: false,// 告訴jQuery不要去設定Content-Type請求頭
            encType:"multipart/form-data",
            success: function(data) {
                alert(data)
            }
        });

    }

Controller

    @RequestMapping(value = "/fileUploadPage.do", method = RequestMethod.POST)
    @ResponseBody
    public String upload(HttpServletRequest req) throws Exception{
        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
        MultipartFile file = mreq.getFile("file");
        String fileName = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String name=req.getSession().getServletContext().getRealPath("/")+
                "upload\\"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'));
        FileOutputStream fos = new FileOutputStream(name);
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
        return name;
    }

在spring.xml中新增

    <!--配置MultipartResolver:用於處理表單中的file-->
    <!-- 檔案上傳配置,這裡id的名稱固定寫法 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>		<!--請求的編碼格式-->
        <property name="maxUploadSize" value="102400000"></property>	<!--檔案最大大小(位元組) 1024*1024*50=50M-->
        <property name="resolveLazily" value="true"/>			<!--resolveLazily屬性啟用是為了推遲檔案解析,以便捕獲檔案大小異常-->
        <property name="uploadTempDir" value="upload"></property>		<!--指定上傳檔案的臨時資料夾,請在專案中建立好目錄。-->
    </bean>