1. 程式人生 > >SpringMVC使用MultipartFile 實現非同步上傳檔案

SpringMVC使用MultipartFile 實現非同步上傳檔案

目的是實現非同步上傳

1.新增pom依賴

新增pom依賴,因為用的ajax,資料需要轉成json的格式進行傳輸,所以還有加入一個JSON jar包:

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency
>
<dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId
>
<artifactId>fastjson</artifactId> <version>1.1.37</version> </dependency>

2.修改配置檔案

applicationContext.xml裡面需要加上:

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property
name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="5400000"></property> </bean>

3.前端頁面上

前端頁面:

    <form  id="uploadForm" name="uploadForm"
        enctype="multipart/form-data">
<input name="messageContent" value="多個引數的情況下">
            <label>檔案</label> <input type="file" name="file">
            <button class="btn" type="button" id="doSave">提交</button>
    </form>
</body>
</html>

需要加入的JS:

<script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>  
<script type="text/javascript" src="js/jquery-ui.min.js"></script>  
<script type="text/javascript" src="js/jquery.form.js"></script>  

JS方法:

<script>
    $(function() {
        $("#doSave")
                .click(
                        function() {
                            $("#uploadForm")
                                    .ajaxSubmit(
                                            {
                                type : 'post',
                                url : "/tmpInfo/method2.do",

        //data:  //注意只要是寫在表單裡面的,都不需要加這個屬性。在controller中可以根據@RequestParam String str獲取到屬性值。    
    contentType : "application/x-www-form-urlencoded; charset=utf-8",
        success: function(data) {
                  //接受到的data還只是一個字串,需要轉成json物件
                  var obj = JSON.parse(data);
                  if(obj.flag==true){
                    alert("上傳成功");
              }else{
                  alert("error");
              }
                },
                error: function (data)//伺服器響應失敗處理函式
                {
                    alert("出錯");
                }  
              });
    });
    });  

controller程式碼:

   @RequestMapping("/method2")  
        @ResponseBody
        public String method2(@RequestParam MultipartFile file,
                @RequestParam String messageContent  ) { 
                //多個引數的話只要多個@RequestParam即可,注意引數名要和表單裡面的屬性名一致
         JSONObject json =new JSONObject();
         System.out.println(messageContent);
            String orgiginalFileName = "";  
            int m =new Random().nextInt(100)+10;
            System.out.println("m="+m);
            String path="D:/"+m+"b.txt";
            try {  
                File newFile =new File(path);
                file.transferTo(newFile);

                String fileName = file.getName();  
                InputStream inputStream = file.getInputStream();  
                String content = file.getContentType();  
                orgiginalFileName = file.getOriginalFilename();  
               System.out.println("fileName: "+fileName+", inputStream: "+ inputStream  
                            +"\r\n content: "+content+", orgiginalFileName: ="+ orgiginalFileName  
                            +"\r\n projectName: ");      
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            json.put("flag", true);
            json.put("message", "success");
            System.out.println(json.toJSONString());
            return json.toJSONString();  
        }