使用ResponseEntity实现对jar内部和外部的数据文件实现下载。
ResponseEntity的泛型可以设置自定义返回值,也可以使用自带的返回值。
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@RequestMapping("/test")
public class TestController {
// 设置返回值
class MyResult<T>{
private int code;
private String msg;
private T data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
@PostMapping("/download/out")
public ResponseEntity<Object> downloadOut(){
try {
// Set the file name
String fileName = "my.xlsx";
// 工程的目录
String prefixPath = System.getProperty("user.dir");
// 文件路径
String filePath = "/data/"+fileName;
// 设置头信息
HttpHeaders headers = new HttpHeaders();
// 设置文件名称
headers.setContentDispositionFormData("attachment", fileName);
// 转化文件
Path path = Paths.get(prefixPath + "/" + filePath);
Resource resource = new InputStreamResource(Files.newInputStream(path));
// 设置返回值
return ResponseEntity.ok()
.headers(headers)
.contentLength(Files.size(path))
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
} catch (IOException e) {
System.out.println("下载文件失败");
MyResult<String> result = new MyResult<>();
result.setCode(-1);
result.setMsg("下载文件失败");
// 返回实体值
return ResponseEntity.ok(result);
}
}
@PostMapping("/download/in")
public ResponseEntity<Object> downloadIn(){
System.out.println("test");
try {
// Set the file name
String fileName = "my.xlsx";
// 文件路径
String filePath = "/data/"+fileName;
// 设置头信息
HttpHeaders headers = new HttpHeaders();
// 设置文件名称
headers.setContentDispositionFormData("attachment", fileName);
System.out.println(filePath);
// 获取资源jar包下的数据文件
ClassPathResource classPathResource = new ClassPathResource(filePath);
Resource resource = new InputStreamResource(classPathResource.getInputStream());
// 设置返回值
return ResponseEntity.ok()
.headers(headers)
.contentLength(classPathResource.contentLength())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
} catch (IOException e) {
System.out.println("下载文件失败");
MyResult<String> result = new MyResult<>();
result.setCode(-2);
result.setMsg("下载文件失败");
// 返回实体值
return ResponseEntity.ok(result);
}
}
}
本文介绍了如何使用Spring框架的ResponseEntity类处理jar内部和外部数据文件的下载请求,包括设置文件名、头信息以及处理异常情况。
4300

被折叠的 条评论
为什么被折叠?



