前端jsp <form action="<%=path%>/admin/user/upload" method="post" enctype="multipart/form-data"> <input type="file" id="filePath" name="filePath" multiple="true" title="请选择图片"/> <input type="submit" /> </form> |
后端代码 public Object upload(HttpServletRequest request) throws IOException { MultipartHttpServletRequest mutli=(MultipartHttpServletRequest) request; MultipartFile mfile = mutli.getFile("filePath");String[] str = new String[] { "image/jpg", "image/gif", "image/png", "image/bmp", "image/pjpeg", "image/jpeg" }; if (mfile != null && !mfile.isEmpty()) { if (!Arrays.asList(str).contains(mfile.getContentType())) { return new RequestResultModel(false, "上传的图片格式不对!"); } } String path="d://dictsyn//";File destDir=new File(path) if (!destDir.exists()) { destDir.mkdir(); } File filepath=new File(path+mfile.getOriginalFilename());//写入文件 common.iojar包 FileUtils.writeByteArrayToFile(filepath, mfile.getBytes()); return null; } |
由于Post一个包含文件上传的Form会以multipart/form-data请求发送给服务器,必须明确告诉DispatcherServlet如何处理MultipartRequest。首先在application.xml中声明一个MultipartResolver:
xml 代码
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <!-- 设置上传文件的最大尺寸为1MB -->
- <property name="maxUploadSize">
- <value>1048576</value>
- </property>
- </bean>