利用ajaxfileupload.js异步上传文件

1、引入ajaxfileupload.js

2、html代码

<input type="file" id="enclosure" name="enclosure">
<button id="upClick" >上传</button>

注意这里的input控件的id和name必须一致;这样在后台利用springMVC接受文件的时候能对应起来;

3、JS代码

    <script type="text/javascript">
      $(document).ready(function(){
          $("#upClick").click(function(){
            $.ajaxFileUpload(
            {
               url:'MyMail/addEnclosure',
               secureuri:false,
               fileElementId:'enclosure',      //文件选择框的id和name要一样的名字
               dataType: 'json',
               success: function (data, status){
           //这里的返回值利用JSON $(
'#filePath').val(data['filePath']); $('#result').html(data['message']); },error: function (data, status, e){ $('#result').html(data['message']); } } ); }); }); </script>

4、springMVC的controller

 1     /***
 2      * 上传附件
 3      * @return
 4      */
 5     @RequestMapping("/addEnclosure")
 6     public @ResponseBody String uploadFile(@RequestParam("enclosure") CommonsMultipartFile file){ 8         JSONObject object = new JSONObject();
 9         object.put("filePath", file.getOriginalFilename());10      String returnJson = "";
11         try {
12             //使用ajaxfileupload.js异步上传文件,返回值乱码,重新编码处理
13             returnJson = new String(JSONObject.fromObject(object).toString().getBytes("utf-8"),"iso-8859-1");
14         } catch (UnsupportedEncodingException e) {
15             e.printStackTrace();
16         }
17         return returnJson;
18     }
原文地址:https://www.cnblogs.com/parryyang/p/5178268.html