SpringMVC实现文件上传方法,只是一个简单的demo,后面有jar下载

1.在spring中配置【上传文件的解析器】

<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<propertyname="defaultEncoding"value="utf-8"/>

<propertyname="maxUploadSize"value="10485760"/><!-- 上传文件限制 -->

<propertyname="maxInMemorySize"value="20480"/><!-- 缓存大小 -->

</bean>

2.前台jsp页面

<form id="fm"action="/springMVC/fileUpload/addfile"  method="post"  enctype="multipart/form-data">

   <inputtype="file"name="myfile"value="">&nbsp;&nbsp;&nbsp;        <inputtype="button"id="submit1"value="提交"/>

    <inputtype="submit"value="submit">

</form>

3.后台Controller

@RequestMapping("/upload") public String upload1(@RequestParam("myfile") MultipartFile file, HttpServletRequest req) throws Exception { String filename = file.getOriginalFilename();// 获取文件名称,带后缀 System.out.println("进入上传!文件名:" + filename); if (!file.isEmpty()) { try { FileOutputStream out = new FileOutputStream("D:wll/"

  • file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(".")) + ".hh"); //这是我自己的拼接的新文件名称:  比如:springmvc.hh InputStream in = file.getInputStream(); int b = 0; while ((b = in.read()) != -1) { out.write(b); } out.flush(); out.close(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } return "success"; }

上面是单个文件上传 ,如果需要多个文件上传,只需要把前台的name改成一样的,后台的Controller接收的参数改成数组,在遍历数组里把单文件的方法复制过来即可:红色是改动的部分

public String upload(@RequestParam("myfile") MultipartFile[] files, HttpServletRequest req) throws Exception { for (MultipartFile file:files) { String filename = file.getOriginalFilename();// 获取文件名称,带后缀 System.out.println("进入上传!文件名:" + filename); if (!file.isEmpty()) { try { FileOutputStream out = new FileOutputStream("D:wll/"+ file.getOriginalFilename().substring(0, file.getOriginalFilename().indexOf(".")) + ".wll"); InputStream in = file.getInputStream(); int b = 0; while ((b = in.read()) != -1) { out.write(b); } out.flush(); out.close(); in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }

return "success"; }

链接是整个springmvc的包,不仅仅有文件上传,可以在Eclipse直接跑起来的

lib