spring MVC 文件上傳

參考博文:http://tzwzero-163-com.iteye.com/blog/1697184java

----------------------------------------如下是該文引用,紅色部分是我添加了一句話---------------------------------web

必須明確告訴DispatcherServlet如何處理MultipartRequest。spring

SpringMVC中提供了文件上傳使用方式以下apache

配置xxx-servlet.xml,添加以下代碼:服務器

 

Xml代碼  收藏代碼mvc

<bean id="multipartResolver"  
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 設置上傳文件的最大尺寸爲1MB -->  
    <property name="maxUploadSize">  
        <value>1048576</value>  
    </property>  
</bean>

  注意這裏的文件尺寸實際上只的是因此文件總大小app

若是配置了文件大小就覺得這你須要配置異常信息控制jsp

因此須要配置異常顯示
spa

Xml代碼  code

<!-- SpringMVC在超出上傳文件限制時,會拋出org.springframework.web.multipart.MaxUploadSizeExceededException -->  
    <!-- 該異常是SpringMVC在檢查上傳的文件信息時拋出來的,並且此時尚未進入到Controller方法中 -->  
    <bean id="exceptionResolver"  
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
        <property name="exceptionMappings">  
            <props>  
                <!-- 遇到MaxUploadSizeExceededException異常時,自動跳轉到/WEB-INF/jsp/error_fileupload.jsp頁面 -->  
                <prop  
                    key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>  
            </props>  
        </property>  
    </bean>

  或者偷懶點,不設置大小,則最終默認是值爲不限制。若是非要控制返回信息,能夠考慮在地應以的異常處理中返回指定格式數據,例如JSON

配置完了頁面上一如既往的須要再form表單中增長:enctype="multipart/form-data"

而後就是須要處理的action了,能夠有兩種方式

第一種方式:

Java代碼  收藏代碼

public String login( @RequestParam MultipartFile file, Model model) {  
………………  
}

 

其中file的名字必須保證與<input type=file>中的那麼屬性值保持一致,若果是多文件上傳,則考慮使用,多文件上傳時各file名也必須一致,不然上傳不成功

Java代碼  

  public String login(@Valid UserInfo userInfo, BindingResult result, @RequestParam MultipartFile[] files, Model model) {  
………………  
}

單文件能夠省略 @RequestParam 多文件則不可省略

第二種方式:

Java代碼  收藏代碼

 這樣也能夠獲取到文件

public ModelAndView handleRequest(HttpServletRequest request,     
            HttpServletResponse response) throws Exception {     
        // 轉型爲MultipartHttpRequest:     
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;     
        // 得到文件:     
        MultipartFile file = multipartRequest.getFile(" file ");    
    }

其實剛纔首先須要配置是加入兩個 jar包:

commons-fileupload-1.2.2.jar

commons-io-2.1.jar

--------------------------------------------------引用結束--------------------------------------------------------------------------

//No.1 本方法是文件+文本域等混合的上傳
@RequestMapping("/upload-mvc-txt.do")
    public String handleFormUpload(@RequestParam MultipartFile[] file1, HttpServletRequest request) {

        String path = request.getSession().getServletContext().getRealPath("/") + "/upload/";
        for(MultipartFile ufile : file1){
            if (!ufile.isEmpty()) {
                System.out.println(path);
                File file = new File(path + new Date().getTime() + ".jpg"); //服務器上新建文件
                try {
                    FileUtils.copyInputStreamToFile(ufile.getInputStream(), file);
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        String uname = request.getParameter("user_name");
        System.out.println(uname);
        return "success";
    }

    @RequestMapping("/upload-mvc.do")
    public String handleFormUpload(MultipartFile file1, HttpServletRequest request) { //請求參數必定要與form中的參數名對應
        System.out.println(file1.getSize());
        if (!file1.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("/") + "/upload/";
            System.out.println(path);
            File file = new File(path + new Date().getTime() + ".jpg"); //新建一個文件
            try {
                FileUtils.copyInputStreamToFile(file1.getInputStream(), file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "success"; //返回成功視圖
        }else {
            return "error"; //返回失敗視圖
        }
    }


    /**
     * 非 spring MVC 方式,即便用了普通的servlet的方式,若是使用了springMVC(需在xml中配置)
     * 此方法將不能正確的上傳文件,緣由是spring mvc會把request從新封裝,導致fileUpload.parseRequest(request);
     * 返回的list爲空。(去掉響應配置便可使用本方法)
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/upload.do")
    public String upPic(HttpServletRequest request, HttpServletResponse response) {
        String appPath = request.getSession().getServletContext().getRealPath("/");
        try{
            //判斷Form是否爲 multipart form
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if(isMultipart){
                FileItemFactory fileItemFactory = new DiskFileItemFactory();//設置工廠

                ServletFileUpload sfu = new ServletFileUpload(fileItemFactory);

                //這裏就是中文文件名處理的代碼,其實只有一行,setHeaderEncoding就能夠了
                sfu.setHeaderEncoding("utf-8");

                List fileItemList = sfu.parseRequest(request);//解析上傳文件數據包

                for(int i=0;i<fileItemList.size();i++){
                    FileItem fileItem = (FileItem)fileItemList.get(i);//遍歷每一個上傳文件

                    if(!fileItem.isFormField()){//判斷是否是上傳的文件
                        String fullFileName = fileItem.getName();//文件全名
                        String fileName = getFileName(fullFileName);//文件名
                        //設置文件存儲在服務器上的路徑
                        String path = appPath + "/upload";
                        if(!new File(path).isDirectory())//若是不存在,則建立目錄
                            new File(path).mkdirs();
                        File file = new File(path, fileName);
                        fileItem.write(file);
                        System.out.println("上傳第" + i + "個文件");
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return "success";
    }

Spring MVC 對文件上傳的支持和與apache-commons的兩個組件的結合仍是很方便的,以上僅僅完成基本的上傳功能,其餘的細節和特性還有待進一步的嘗試。

相關文章
相關標籤/搜索