依赖
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
解析器
<!--文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--编码--> <property name="defaultEncoding" value="UTF-8"/> <!--最大字节--> <property name="maxUploadSize" value="10000000000"/> <!--单文件大小--> <property name="maxUploadSizePerFile" value="50000000"/> </bean>
表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上传</title> </head> <body> <form action="/file/fileUploads" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> 作者: <input type="text" name="author"/> <input type="submit" value="提交"/> </form> </body> </html>
@Controller @RequestMapping("/file") public class FileController { @RequestMapping("/fileUpload") /** * MultipartFile 选择的文件 */ public String fileupload(HttpSession session,MultipartFile file,String author) throws IOException { System.out.println("作者:"+author); /** * 如何处理文件 */ if(!file.isEmpty()){ //获取文件名称 String fileName=file.getOriginalFilename(); //获取到需要上传的路径 String realPath = session.getServletContext().getRealPath("/WEB-INF/upload"); //创建文件对象 File uploadfile=new File(realPath+"\"+fileName); //如何上传文件 file.transferTo(uploadfile); } return "index"; } }
多文件上传
表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件上传</title> </head> <body> <form action="/file/fileUploads" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFiles"/> <input type="file" name="uploadFiles"/> <input type="file" name="uploadFiles"/> 作者: <input type="text" name="author"/> <input type="submit" value="提交"/> </form> </body> </html>
@RequestMapping("/fileUploads") /** * MultipartFile 选择的文件 */ public String fileUploads(HttpSession session,MultipartFile[] uploadFiles,String author) throws IOException { System.out.println("作者:"+author); System.out.println(uploadFiles); /** * 如何处理文件 */ for (MultipartFile file:uploadFiles){ if(!file.isEmpty()){ //获取文件名称 String fileName=file.getOriginalFilename(); //获取到需要上传的路径 String realPath = session.getServletContext().getRealPath("/WEB-INF/upload"); //创建文件对象 File uploadfile=new File(realPath+"\"+fileName); //如何上传文件 file.transferTo(uploadfile); } } return "index"; } }
文件下载
(1)传统方法
(2)Spring MVC框架技术