Spring boot的文件上传

微信公众号:Java患者

专注Java领域技术分享

前言

       文件上传的功能,基本上在所有的企业级应用都会有,那么在一个前后端分离的架构中,文件上传的功能又是如何去实现的呢。一般前端采用的是单页面应用,不会发生刷新和表单的提交,大部分都是异步完成的,他提交文件的时候,只是提交一个文件的路径上来。

文件上传测试用例

  @Test
  public void whenUploadSuccess() throws Exception {
      String result = mockMvc.perform(fileUpload("/file")
              .file(new MockMultipartFile("file", "test.txt", "multipart/form-data", "hello upload".getBytes("UTF-8"))))
              .andExpect(status().isOk())
              .andReturn().getResponse().getContentAsString();
      System.out.println(result);
  }

        MockMultipartFile对象用来构建我们的文件以及文件上传的参数,第一个参数指定上传时参数的name,第二个参数指定上传的文件名字,第三个参数指定enctype类型,第四个参数就是上传的文件。

下面是我们文件上传的Controller:

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


  // 放文件的路径
  private String folder = "E:\\WorkSpace\\security\\security-demo\\src\\main\\java\\com\\zhaohong\\web\\controller";


  @PostMapping
  public FileInfo upload(MultipartFile file) throws Exception {
    System.out.println(file.getName());
    System.out.println(file.getOriginalFilename());
    System.out.println(file.getSize());
    File localFile = new File(folder, new Date().getTime() + ".txt");
    // 把上传的文件写在本地
    file.transferTo(localFile);
        return new FileInfo(localFile.getAbsolutePath());
  }
 }

        需要注意的是,以上是我们代码的方便,而在我们实际的开发中,通常把文件存在到云服务上面,如阿里云、青牛云。

文件下载测试用例

 下面是根据文件id,下载文件的代码:

  @GetMapping("/{id}")
  public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {


    try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
        OutputStream outputStream = response.getOutputStream();) {


      response.setContentType("application/x-download");
      response.addHeader("Content-Disposition", "attachment;filename=test.txt");
      // commons-io包下的
      // 包输入流写入输出流
      IOUtils.copy(inputStream, outputStream);
      outputStream.flush();
    } 
  }

        上面代码中把流的声明写在try的括号里面,他会在代码运行结束,自动帮我们关闭流,这是jdk1.7的特性。

        到目前前为止。我们的文件上传下载已经讲完了,各位小伙伴们别忘了点关注哦。

查看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值