SpringBoot实现文件上传与下载

目录

文件上传

文件下载


文件上传

配置文件中配置文件上传相关参数

application.yml配置

#自定义属性
file:
  path: D:/public/

spring:
  servlet:
    multipart:
      #开启文件上传
      enabled: true
      #单个文件最大限制
      max-file-size: 100MB
      #单个文件最多请求文件
      max-request-size: 100MB

    #表示所有的访问都要经过静态资源路径
    mvc:
      static-path-pattern: /**
    #手动加上静态资源的路径
    resources:
      static-locations: file:${file.path}

简单的html.页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>文件上传与下载</h1>
    <form action="/file/upload" method="post" enctype="multipart/form-data">
        <label>选择文件</label> <input type="file" name="file"><br>
        <input type="submit" value="上传文件">
    </form>
    <h1><a href="/file/download">文件下载</a></h1>
</body>
</html>

 

文件上传upload

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.path}")
    private String filePath;

    @RequestMapping("/upload")
    public String fileUpload(MultipartFile file) throws IOException {
        //应该将上传的文件名修改成唯一的不重复的文件名再存储到硬盘上

        //先获取原来的文件
        String oldFileName = file.getOriginalFilename();
        //获取文件后缀
        String houZhui = oldFileName.substring(oldFileName.lastIndexOf("."));
        //拼接新字符串
        String newFilename = UUID.randomUUID()+houZhui;
        //将文件名和路径拼接,并实例化一个对象
        File uploadFile = new File(filePath+newFilename);
        file.transferTo(uploadFile);


        String res = "文件:" + oldFileName +"上传成功";
        return res;
    }
}

 

文件下载

 文件下载其实就是文件的 copy,也就是I/O操作

 @RequestMapping("/download")
    public void fileDownload(HttpServletRequest request, HttpServletResponse response) {
        File file = new File("d:/public/1.txt");
        //设置响应头和客户端保存的文件名
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition","attachment;fileName="+file.getName());

        //文件复制
        try(FileInputStream in = new FileInputStream(file);
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bin = new BufferedInputStream(in);
            BufferedOutputStream bout = new BufferedOutputStream(out)) {
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = bin.read(buffer)) != -1) {
                //输出
                bout.write(buffer,0,len);
            }
        }catch (Exception e) {
        }

    }

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w7486

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值