Springboot下载文件

下载文件,实现在线和下载到本地

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.zjgsu.sdc.controller;

import com.zjgsu.sdc.pojo.resquest.Name;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Slf4j
@RestController
public class DownloadController {

@Value("${sdc.download.path}")
private String filepath;

@GetMapping("/download/{file}")
public ResponseEntity<FileSystemResource> download(@PathVariable String file) {
// if(file == null) {
// log.info("文件为空");
// }
String path = filepath + file;

log.info("{}下载中", file);
FileSystemResource fileSystemResource = new FileSystemResource(path);
if(!fileSystemResource.exists()){
log.info("文件不存在");
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().headers(getResponseHeaders(file)).body(fileSystemResource);
}

public HttpHeaders getResponseHeaders(String filename) {
HttpHeaders headers = new HttpHeaders();
ContentDisposition.Builder builder = ContentDisposition.builder("inline");
// inline表示播放,attachment为下载到本地
if (StringUtils.hasText(filename)) {
builder.filename(filename, StandardCharsets.UTF_8);
}
headers.setContentDisposition(builder.build());
headers.setContentType(new MediaType("video", "mp4"));
return headers;
}
}

下载二进制文件

1
2
3
4
5
6
7
8
9
@GetMapping(value = "/download/{file}")
public FileSystemResource download(@PathVariable String file) {
if(file == null) {
log.error("file为空");
}
String path = filepath + file;
log.info("{},下载中", file);
return new FileSystemResource(path);
}

本文作者:jujimeizuo
本文地址https://blog.jujimeizuo.cn/2021/04/22/springboot-download-file/
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0 协议。转载请注明出处!