ㅤㅤㅤ
ㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ(对于不屈不挠的人来说,没有失败这回事。——俾斯麦)
ㅤㅤㅤ
ㅤㅤㅤ
ㅤㅤㅤㅤㅤㅤㅤㅤㅤ
版本信息
springboot:2.3.7
java: 1.8
用到的工具包
guava:28.0
swagger-annotations:1.5.20
spring-web:5.2.11
lombok:1.18.16
tomcat-embed-core:9.0.39
示例代码
package com.m7.v7.serverbase.interfaces.controller.file;
import com.google.common.base.Strings;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@Api(tags = "文件上传/下载API")
@RestController
@RequestMapping(value = "/file")
@Slf4j
public class FileController {
String fileBaseDir = "/nfs/test";
@ApiOperation("文件下载")
@GetMapping("/download/**")
public void downloadFile(@RequestParam(required = false, name = "name") String name,
HttpServletRequest request,
HttpServletResponse response) {
log.info("basedir: " + fileBaseDir);
String filepath = request.getServletPath();
// 截取url 拼接真实的文件夹路径
String[] splitPathList = filepath.split("/");
StringBuilder fullPath = new StringBuilder(fileBaseDir);
for (int i = 0; i < splitPathList.length; i++) {
if (i > 3) {
fullPath.append("/").append(splitPathList[i]);
}
}
File file = new File(String.valueOf(fullPath));
if (!file.exists()) {
log.info("文件未找到: " + fullPath);
response.setStatus(404);
} else {
if (Strings.isNullOrEmpty(name)) {
name = file.getName();
}
ServletContext context = request.getServletContext();
String mimeType = context.getMimeType(String.valueOf(fullPath));
if (mimeType == null) {
mimeType = "application/octet-stream";
log.info("context getMimeType is null");
}
response.setContentType(mimeType);
response.setContentLength((int) file.length());
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", name);
response.setHeader(headerKey, headerValue);
try {
InputStream myStream = new FileInputStream(String.valueOf(fullPath));
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
} catch (IOException e) {
log.error("downloadFile error", e);
}
}
}
}