Springboot 文件上传、下载

  • 导入pom.xml必要的包

      <dependency>
          <groupId>commons-lang</groupId>
          <artifactId>commons-lang</artifactId>
          <version>2.6</version>
      </dependency>
    
      <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.4</version>
      </dependency>
    
  • 编写控制类

@RestController
@RequestMapping("/file")
public class FileController {
    //上传文件  往后拖有测试类
    
    @PostMapping("/upload")
    public FileInfo upload(MultipartFile file) throws IOException {
 
		//上传文件指定路径
        String path = "F:\\bookshop-admin\\src\\main\\java\\com\\lesson\\spring\\web\\controller";
        
        //后缀 提取 .txt
        String extention = StringUtils.substringAfterLast(file.getOriginalFilename(),".");
        
		//文件名编写,此处用了时间戳来命名 + 后缀.txt
        File localfile = new File(path,new Date().getTime()+"."+extention);
        
     	//文件复制
        file.transferTo(localfile);
        
		//创建文件
        return new FileInfo(localfile.getAbsolutePath());
    }

    //下载文件
    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //要下载的文件路径 真实项目中一般根据 ID 拿取地址
        String filePath = "C:\\Users\\admin\\Pictures\\123.txt";
        
        try(InputStream inputStream = new FileInputStream(filePath); //这样写的目的是在TRY下会自动关闭流
            OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition","attachment;filename=test.txt");

            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();

        }
    }
}

  • 测试
//上传 (下载直接访问页面即可下载)
 @Test
    public void whenUploadSuccess() throws Exception {
        String result = mockMvc.perform(fileUpload("/file/upload")
                .file(new MockMultipartFile("file","testFile.txt","multipart/form-data","hello upload".getBytes("UTF-8"))))
                .andExpect(status().isOk())
                .andReturn().getResponse().getContentAsString();
        System.out.println(result);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值