ajax上传文件
private static final String FILE_SEPARATOR = System.getProperties().getProperty("file.separator"); @ResponseBody @RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = "application/json") public Map<String,String> uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception { Map<String, String> map = new HashMap<String, String>(); try { String realPath = request.getSession().getServletContext().getRealPath(FILE_SEPARATOR); StringBuffer realPathSbf = new StringBuffer(realPath); realPathSbf.append(FILE_PATH); CommonsMultipartFile importFile = (CommonsMultipartFile) request.getFile("file"); String fileName = importFile.getOriginalFilename(); String allPath = realPathSbf.append(FILE_SEPARATOR).append(fileName).toString(); InputStream is = importFile.getInputStream(); File file = new File(allPath); FileUtils.copyInputStreamToFile(is,file); String url = jssService.uploadResourceWithName(file); FileUtils.forceDelete(file); map.put("url", url); map.put("yn", SuccessEnum.YES.getCode()); }catch (Exception e){ map.put("yn",SuccessEnum.NO.getCode()); logger.error("上传附件异常",e); } return map; } $("#uploadBtnFile").bind("click", function () { var file = $("#filePic").val(); if (file == null || file == "") { alert("请添加上传文件"); return; } var formUrl = "/qc/basic-data/uploadFile"; var formData = new FormData(); formData.append("file", $('#filePic')[0].files[0]); $.ajax({ url: formUrl, data: formData, type: "post", cache: false, processData: false, contentType: false, success: function (data) { if (data.yn == 1) { alert("上传成功"); $("#attachmentUrl").val(data.url); } else { alert("上传失败"); } $('#fileUploadBtn').hide(); }, error: function (data) { alert("上传失败!"); } }) }); <div class="alert alert-result" id="fileUploadBtn"> <i class="close alert-close" id="fileUploadBtnClose"></i> <div class="info"> <input type="hidden" id="attachmentUrl" name="attachmentUrl"/> <input type="file" name="filePic" id="filePic"/><br /><br /><br /> <a class="btn-c2 btn-h1" id="uploadBtnFile" name="uploadBtnFile" href="#">上传文件</a> </div> </div>