实现文件上传与下载功能,主要涉及5个文件,maven配置文件pom.xml ,application.yml配置文件,用户交互界面index.jsp,UpanddownController控制层代码,启动文件Application。
github下载地址https://github.com/1731lin/springbootUpDownload
1.maven配置文件pom.xml 通过maven统一管理jar包,导入工程时需要导入对应的jar包才能正常运行。这里使用了文件上传工具。
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.application.yml
默认加载路径为http://localhost:8080/index.jsp
server:
port:8080
context-path:/index
spring:
servlet:
multipart:
max-request-size: 30MB#单个文件最大大小
max-file-size: 50MB#上传数据总大小
3.用户交互页面jsp
enctype="multipart/form-data"声明表单数据有多部分构成,既有文本数据,又有二进制数据。
<h1>用户上传文件</h1>
<form action="/files/upload" method="post" enctype="multipart/form-data">
<input type="file" name="multipartFile"/>
<input type="submit" value="上传文件"/>
</form>
<hr/>
<h1>用户文件下载</h1>
<a href="/files/download?filename=下载1.txt">下载1.txt</a>
<a href="/files/download?filename=下载2.txt">下载2.txt</a>
使用post请求上传文件,get请求下载文件,在controller层处理。
4.controller
@RequestMapping(value = "download")
public void download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
String basePath = request.getSession().getServletContext().getRealPath("/files/download"); //读取文件内容
FileInputStream is = new FileInputStream(new File(basePath, filename)); response.setHeader("content-disposition", "inline;fileName=" + URLEncoder.encode(filename, "UTF-8"));
ServletOutputStream os = response.getOutputStream(); System.out.println("duwnload文件------------"); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os);
}
MultipartFile 这个类一般是用来接受前台传过来的文件
@RequestMapping(value = "upload",method = RequestMethod.POST) public String upload(MultipartFile multipartFile, HttpServletRequest request) throws IOException { System.out.println("路径 = " + request.getSession().getServletContext().getRealPath("/"));//获取项目根路径
System.out.println("文件名 = " + multipartFile.getOriginalFilename()); System.out.println("文件类型 = " + multipartFile.getContentType()); System.out.println("文件大小 = " + multipartFile.getSize());
String realPath = request.getSession().getServletContext().getRealPath("/files");
File file = new File(realPath, new SimpleDateFormat("yyyy-MM-dd").format(new Date())); if(!file.exists())
file.mkdirs();
String originalFilename = multipartFile.getOriginalFilename();
String extension = FilenameUtils.getExtension(originalFilename);
String newName = UUID.randomUUID().toString().replaceAll("-", "") + new SimpleDateFormat("YYYYMMddHHmmss").format(new Date()) + "." + extension; multipartFile.transferTo(new File(file, newName)); return "redirect:/upload.jsp";
}