Spring MVC+$.ajaxFileUpload 上传文件

maidou0 2015-03-10

spring MVC配合ajaxFileUpload 上传文件。

想要使用ajaxFileUpload来上传文件,必须引入jquery和ajaxfileupload.js才行。

view端form的enctype="multipart/form-data"要设定好,<input type="file" name="uploadFile" id="uploadFile">这里file控件的ID设置为uploadFile,这个一会儿会用到。

//点击上传按钮,触发事件

  function uploadCsvFile(){
   $.ajaxFileUpload({

    //上传的URL
    url : "uploadListData",
    secureuri : false,

    //除了文件以外还需要传进去一些字段
    data : {
     api_token : document.ExcelDownUploadForm.api_token.value
    },

    //这里的fileElementId就是之前页面上file控件的ID
    fileElementId : "uploadFile",

    //指定返回的类型是json
    dataType: 'json',

    //成功的回调方法
       success:function(retdata) {
        if (retdata.successCode == '1') {
         document.getElementById("uploadErrorMessageSpanId").innerHTML="";
         document.getElementById("uploadAlertMessageSpanId").innerHTML=retdata.successMessage[0];
        } else if (retdata.failureCode = '1') {
         document.getElementById("uploadAlertMessageSpanId").innerHTML="";
         document.getElementById("uploadErrorMessageSpanId").innerHTML=retdata.failureMessage[0];
        }
    }, 

    //失败的回调方法
    error : function(retdata, status, e) {
     alert(e);
    } 
   });
  }

//springMVC

 @RequestMapping(value = "/uploadListData")
 @ResponseBody
 public void uploadListData(Model model,@RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletResponse response) throws Exception {

//不设置ContentType,页面上会提示你下载,所以只能自己往response里面写json

  response.setContentType("text/html; charset=utf-8");
  PrintWriter out = null;

//这里用了jackson生成json串
  ObjectMapper mapper = new ObjectMapper();
     mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, Boolean.TRUE);
     String json = mapper.writeValueAsString(responseJsonVO);
  try {
   out = response.getWriter();
   out.append(json);
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (out != null) {
    out.close();
   }
  } 

}

相关推荐