1.文件的上传
- 引入相关依赖
commons-fileupload - 准备文件上传表单
- 表单提交方式必须为post
- 表单enctype必须为multipart/form-data
- 表单提供选择文件窗口
input type=“file” name=“file”
- 开发文件上传controller
@RequestMapping("upload")
public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
System.out.println("获取文件名称:"+file.getOriginalFilename());
System.out.println("获取文件类型:"+file.getContentType());
//根据相对路径获取绝对路径
String realPath = request.getSession().getServletContext().getRealPath("files");
//创建日期文件夹
String dataDir = new SimpleDateFormat("yyy-MM-dd").format(new Date());
File finnalPath = new File(realPath, dataDir);
if(!finnalPath.exists()){
finnalPath.mkdirs();
}
//上传文件
file.transferTo(new File(finnalPath,file.getOriginalFilename()));
return "upload";
}
注意:在springboot默认上传文件的大小为20485760===10M
2.文件的下载
- 在项目中准备下载目录后将下载文件放入指定目录中
- 在系统中提供下载文件的超级链接
- 开发controller完成下载功能
@RequestMapping("download")
public String download(String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
//根据文件名去指定目录下读取文件
String realPath = request.getSession().getServletContext().getRealPath("files/2019-07-19");
//读取文件
FileInputStream fs = new FileInputStream(new File(realPath, filename));
//设置响应头信息
response.setHeader("content-disposition","inline;filename="+ URLEncoder.encode(filename,"UTF-8"));
//设置响应类型
String mimeType = request.getSession().getServletContext().getMimeType("." + FilenameUtils.getExtension(filename));
response.setContentType(mimeType+";charset=UTF-8");
//获得输出流
ServletOutputStream os = response.getOutputStream();
IOUtils.copy(fs,os);
IOUtils.closeQuietly(fs);
IOUtils.closeQuietly(os);
return null;
}