文件上传和下载

文件上传

  1. 引入依赖
<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3.1</version>
</dependency>
  1. form表单
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
     <input type="file" name="file"> <br>
     <input type="submit" value="上传">
 </form>
  1. 后台代码
@ResponseBody
 @RequestMapping("upload")
 public String upload(MultipartFile file, HttpSession session){
     //1. 获得 upload的路径
     String realPath = session.getServletContext().getRealPath("/upload/img");
     //2. 判断文件夹是否存在
     File file1 = new File(realPath);
     if(!file1.exists()){
         file1.mkdirs();
     }
     //3.获取文件真实名字
     String originalFilename = file.getOriginalFilename();
     //4. 为了防止同一个文件多次上传发生覆盖  拼接时间戳
     String name = new Date().getTime()+"_"+originalFilename;
     //5.文件上传
     try {
         file.transferTo(new File(realPath,name));
     } catch (IOException e) {
         e.printStackTrace();
     }
     return "上传成功";
 }
  1. 上传细节
    1. 默认上传单个文件大小: 1MB

    2. 默认批量上传文件大小为: 10MB

    3. 配置上传文件的大小(可选 KB MB GB TB)

    4. 配置上传文件大小

spring:
  servlet:
    multipart:
      max-file-size: 10MB     #单个文件大小       默认1MB
      max-request-size: 90MB #同时上传多个文件大小 默认10MB

文件下载

  1. 后台实现
@RequestMapping("download")
 public void download(String filename, HttpSession session, HttpServletResponse response) throws Exception {
     //获得文件存放的路径
     String realPath = session.getServletContext().getRealPath("/upload/file");
     //创建文件夹
     File file = new File(realPath, filename);
     //设置响应类型及编码格式
     String extension = FilenameUtils.getExtension(filename);
     String mimeType = session.getServletContext().getMimeType("." + extension);
     response.setContentType(mimeType+";charset=UTF-8");
     //指定下载方式
     response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(filename,"UTF-8"));
     //下载
     ServletOutputStream outputStream = response.getOutputStream();
     FileUtils.copyFile(file, outputStream);
     outputStream.close();
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值