springmvc 使用ajx上传文件 不设置form enctype

     最近在做一个小项目 碰到这个问题 解决方案如下

     1.js代码如下 获取当前form 转换为formdata ajax提交到后台

var form = $("#importForm");
var formData =new FormData($scope._window.find("#importForm"));
$.ajax({
                           type:"POST",
                         data:formData,
                         processData:false,
                         contentType:false,
                        url:$scope.webpath.p0path+"/cps-p0-web/importpiccontroller/importPickticket",
                        success:function(data){
                           alert("上传成功");
                        },
                        exception:function(data,textStatus){

                            }
                    });

后台代码解析

@ResponseBody
    @RequestMapping(value = "/importPickticket")
    public ResponseModel importPickticket(HttpServletRequest request,HttpServletResponse response) throws BussinessException{
        ResponseModel responseModel = new ResponseModel();
        try{
//上传文件后保存文件 String filePath
= FileUpload.fileUpload(request, response); responseModel.setSuccess(true); }catch (BussinessException e) { }catch (Exception e) {

}
return null; } return null; }

//FileUpload 代码

public class FileUpload {

public static String fileUpload(HttpServletRequest request, HttpServletResponse response) {
try {
//文件服务器名称
StringBuffer rename = new StringBuffer();
//
ServletContext servletContext = request.getSession().getServletContext();
//获取服务器保存路径
String pathUrl = servletContext.getRealPath(PropertyPlaceholder.getProperty("fileUploadPath").toString());
//解析器解析request的上下文
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(servletContext);
//先判断request中是否包涵multipart类型的数据
if (multipartResolver.isMultipart(request)) {
// 再将request中的数据转化成multipart类型的数据
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 获取文件名
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile((String) iter.next());
if (file != null) {
rename.append(new Random().nextInt(99999)).append("_").append(System.currentTimeMillis()).append(file.getOriginalFilename());
File localFile = new File(pathUrl + "/" + rename.toString());
// 写文件到本地
file.transferTo(localFile);
}
}
}
return pathUrl + "/" + rename.toString();
} catch (Exception e) {
throw new BussinessException("FileUpload.fileUpload.BusinessException", e);
}
}
}

 

posted on 2017-04-25 11:32  zzz初见  阅读(843)  评论(0编辑  收藏  举报

导航