Spring Boot文件上传与下载的实现

Spring Boot文件上传后端代码实现:

@PostMapping
public FileInfo upload(MultipartFile file) throws IOException {

    System.out.println("fileName: " + file.getName());
    System.out.println("originalFilename: " + file.getOriginalFilename());
    System.out.println("fileSize" + file.getSize());
    File localFile = new File(folder + System.currentTimeMillis() + ".txt");
    file.transferTo(localFile);
    return new FileInfo(localFile.getAbsolutePath());
}

Spring Boot文件下载后端代码实现

@GetMapping("/{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
    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");
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

阅读更多
想对作者说点什么? 我来说一句

gradle实战之文件上传进度条

2014年06月22日 508KB 下载

SpringBoot上传文件实例下载

2017年03月11日 96KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭