Rest上传下载文件

测试用例

    @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);
    }

 

控制器

@RestController
@RequestMapping("/file")
public class FileController {
    
    @PostMapping("/upload")
    //与测试用例的第一个参数名字对应
    public FileInfo update(MultipartFile file) throws Exception {
    
        System.out.println(file.getContentType());
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        
        String path = "/Users/zhailiang/Documents/my/roncoo/workspace/bookshop-admin/src/main/java/com/lesson/spring/web/controller";
        //获取扩展名
        String extention = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
        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 Exception {
        String filePath = "/Users/zhailiang/Documents/my/roncoo/workspace/bookshop-admin/src/main/java/com/lesson/spring/web/controller/1494176321973.txt";
        try(InputStream inputStream = new FileInputStream(filePath);
            OutputStream outputStream = response.getOutputStream();){
            
            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");
            
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
        
    }

}
 

 */
public class FileInfo {
    
    public FileInfo(String path) {
        this.path = path;
    }
    
    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }
    
}

 

spring.http.multipart.max-file-size = 10MB

上传大小限制设置

你可能感兴趣的:(spring,boot)