前台代码:
注意:文件上传时必须加该属性!
SpringMVC配置文件:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 如果上传后出现文件名中文乱码可以使用该属性解决 --> <property name="defaultEncoding" value="UTF-8" /> <!--设置允许上传的最大文件大小,以字节为单位计算。当设为-1时表示无限制,默认是-1。--> <property name="maxUploadSize" value="2000000"/> <!-- 设置在文件上传时允许写到内存中的最大值,以字节为单位计算,默认是10240 --> <!-- 但是经实验,上传文件大小若小于此参数,则不会生成临时文件,很尴尬,故改为2048 --> <!--maxInMemorySize最好设稍微小点--> <property name="maxInMemorySize" value="2048"/> <!-- 跟maxUploadSize差不多,不过maxUploadSizePerFile是限制每个上传文件的大小, 而maxUploadSize是限制总的上传文件大小 --> <property name="maxUploadSizePerFile" value="1024000"/> <!--适用于大文件,判断是否要延迟解析文件,即当需要获取文件信息时才会去解析请求数据, 这种方式用了懒加载的思想。--> <property name="resolveLazily" value="true"/> <!--设置上传文件时的临时目录,默认是Servlet容器的临时目录--> <property name="uploadTempDir" value="/upload"/> </bean>
后台代码:
@RequestMapping("/ddm/test/upload") public String uploadOk(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws ServletException,IOException{ String contentType = file.getContentType(); //随机创建唯一名称,防止名称相同而发生错误! String randomname = UUID.randomUUID().toString().replace("-", ""); String fileName = randomname + file.getOriginalFilename(); String filePath = "F:\\upload\\";//这里路径写死了,实际开发时具情况而定! try { File targetFile = new File(filePath); if(!targetFile.exists()){ targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath+fileName); out.write(file.getBytes()); out.flush(); out.close(); } catch (Exception e) { // TODO: handle exception } //返回json return "member/upload/upOk"; }
一次选择多个文件的多文件上传:
<input type="file" name="files" value="" multiple="multiple">