Springboot 文件上传

耗尽温柔 提交于 2019-11-28 07:22:57
  • 导入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);
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!