使用spring包下载返回
重点是使用ClassPathResource读取文件,如果用传统new File()打包在Linux上运行时就不支持
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileDownloadController {
@GetMapping("/downloadTemplate")
public ResponseEntity<Resource> downloadTemplate() throws IOException {
// 假设应用部署后,classpath根目录下的相对路径映射到服务器文件系统中的实际位置
Path filePath = Paths.get("src/main/resources/template/Template.dbf");
// 如果应用打包成jar运行,则不能直接从文件系统读取,需要通过ClassLoader加载资源