springMVC对文件上传做了简化,springboot对此做了更进一步的简化。
java中的文件上传一共涉及两个组件,1.ComminsMultipartResolver 2.StandardServletMultipartResolver,其中ComminsMultipartResolver 使用commons-fileupload来处理multipart请求,而StandardServletMultipartResolver则是基于Servlet3.0来处理multipart请求,Tomcat7.0开始就支持Servlet3.0了,而spring boot 2.0.4内嵌的Tomcat为Tomcat8.5.32,
因此说白了就是使用springboot上传文件可以做到零配置,。
单文件上传
首先创建springboot项目并添加spring-boot-starter-web依赖
在resources目录下的templates目录创建upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--是actiob不是about,本人因为这个小问题研究了小半天--> <!--上传接口是main/upload,注意使用post提交,enctype是multipart/form-data--> <form action="main/upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file" value="选择文件" /> <input type="submit" value="上传"/> </form> </body> </html>
因为是在templates目录下创建的.html用户是不能直接访问的,我们通过下面代码访问
@GetMapping public String upload() { return "upload"; }
package com.example.demo.controller; import com.example.demo.entity.Book; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; @Controller @RequestMapping("/main") public class main { //跳转到upload.html页面 @GetMapping public String upload() { return "upload"; } //声明时间格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); @RequestMapping(value = "/upload",method = RequestMethod.POST) @ResponseBody public String update(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest req) { String realPath = req.getSession().getServletContext().getRealPath("/uploadFile/"); String format = sdf.format(new Date()); File folder = new File(realPath + format); if (!folder.isDirectory()) { folder.mkdirs(); } String oldName = uploadFile.getOriginalFilename(); String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length()); try { //上传主要是transferTo方法 uploadFile.transferTo(new File(folder, newName)); String filePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServletPath() + "/uploadFile/" + format + newName; return filePath; } catch (IOException e) { e.printStackTrace(); } return "上传失败"; } }
当然如果开发者需要对图片上传的细节进行配置,也是允许的,下面代码是我通过.yml配置的
spring: servlet: multipart: enabled: true #表示十分开启文件上传,默认为true file-size-threshold: 0 #文件写入磁盘的值,默认为0 resolve-lazily: false #是否延迟解析,默认为false location: E://temp #表示文件临时保存位置 max-file-size: 1MB #上传单个文件最大大小,默认为1MB max-request-size: 10MB #多文件上传总大小,默认为10MB
多文件上传
前端代码
在原本的代码中添加multiple表示支持选择多个文件 <input type="file" name="file" value="选择文件" multiple>
修改控制器:代码
修改接收的值就可以了,将其修改为数组,后面遍历数组拿到文件就可以了
文件下载
前端创建HTML
<a href="download">下载</a>
创建File_Download 控制类
package com.example.demo.controller; import java.io.*; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class File_Download { //实现Spring Boot 的文件下载功能,映射网址为/download @RequestMapping("/download") public String downloadFile(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { // 获取指定目录下的第一个文件 File scFileDir = new File("E://music"); File TrxFiles[] = scFileDir.listFiles(); System.out.println(TrxFiles[0]); //下载的文件名 String fileName = TrxFiles[0].getName(); // 如果文件名不为空,则进行下载 if (fileName != null) { //设置文件路径 String realPath = "E://music/"; File file = new File(realPath, fileName); // 如果文件名存在,则进行下载 if (file.exists()) { // 配置文件下载 response.setHeader("content-type", "application/octet-stream"); response.setContentType("application/octet-stream"); // 下载文件能正常显示中文 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 实现文件下载 byte[] buffer = new byte[1024]; FileInputStream fis = null; BufferedInputStream bis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); OutputStream os = response.getOutputStream(); int i = bis.read(buffer); while (i != -1) { os.write(buffer, 0, i); i = bis.read(buffer); } System.out.println("Download the song successfully!"); } catch (Exception e) { System.out.println("Download the song failed!"); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return null; } }