如何HttpServletRequest文件对象并储存

由于HttpServletRequest不能直接取出文件数据,所以将其强制转换为MultipartHttpServletRequest

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multipartRequest.getFiles("files");

POST

/*提交表单*/ function myupload() { $.ajax({ url:"/exUploadController.do?uploadTest", type : "POST", async: false, cache: false, //此处设置false contentType: false,//必须设置false ,formupload1表单中必须设置enctype="multipart/form-data" processData: false, //必须设置fals data :new FormData(document.getElementById("myForm")), success:function (data) { alert(data); }, error:function (XMLHttpRequest, textStatus, errorThrown) { console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); } }) }

Servlet

HttpServletRequest request;       //获取上传图片 MultipartHttpServletRequest mureq = (MultipartHttpServletRequest) request; Map<String, MultipartFile> files = mureq.getFileMap(); MultipartFile file =null; if (files != null &&files.size()> 0) { Map.Entry<String, MultipartFile> f = files.entrySet().iterator().next(); file = f.getValue(); }       //获取项目部署的路径       String rootPath = request.getSession().getServletContext().getRealPath("https://www.jb51.net/");      //获取上传图片的名称       String fileName = file.getOriginalFilename();             //获取上传图片的大小       float size = file.getSize()       //在path路径下创建一个文件       File newFile = new File(path);       //判断文件是否存在       if(!newFile.exists()) {         newFile.mkdirs();//不存在的话,就开辟一个空间       }       //将上传的文件存储       file.transferTo(newFile);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wxwfpd.html