SpringBoot 文件上传与下载
功能
- 实现文件上传
- 实现文件下载
- 实现文件通过uri直接访问
代码
- controller
该类只做了一些参数校验
/**
* 文件上传
*/
@Controller
@RequestMapping("/file")
public class FileController {
@Autowired
private FileService fileService;
@Autowired
private ParamsCheckService paramsCheckService;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity upload(@RequestParam("file") MultipartFile file) throws BizException {
// 默认状态成功
ResponseEntity responseEntity = new ResponseEntity();
// 文件校验
paramsCheckService.checkFile(file);
responseEntity.setData(fileService.save(file));
// 以上流程没抛异常说明成功
return responseEntity;
}
/**
* 使用流将图片输出
* @param fileName
*/
@RequestMapping(value = "/downFile", method = RequestMethod.GET)
public void getImage(@RequestParam("name") String fileName) throws BizException {
fileService.transFile(fileName);
}
}
- service
@Service
public class FileServiceImpl implements FileService {
private final static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
@Autowired
private ContextService contextService;
@Value("${UPLOAD_FILE_FOLDER}")
private String UPLOAD_FILE_FOLDER;
// 项目上线修改为域名
private String pathPrefix = "http://127.0.0.1:8888/";
/**
* @param file
* @return
* @throws BizException
*/
@Override
public String save(MultipartFile file) throws BizException {
StringBuffer filePath = new StringBuffer();
//获取文件名
String fileName = file.getOriginalFilename();
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//重新生成文件名
fileName = UUIDStringUtil.randomUUID().concat(suffixName);
try {
//将图片传输到文件夹
file.transferTo(new File(UPLOAD_FILE_FOLDER, fileName));
filePath.append(pathPrefix).append(fileName);
return filePath.toString();
} catch (Exception e) {
throw new BizException(EnumCode.SYSERROE, e.getMessage());
}
}
@Override
public void transFile(String formFileName) throws BizException {
HttpServletResponse response = contextService.getHttpServletResponse();
HttpServletRequest request = contextService.getHttpServletRequest();
try {
String userAgent = request.getHeader("User-Agent");
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
} else {
// 非IE浏览器的处理:
formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setCharacterEncoding("utf-8");
fileDownload(response.getOutputStream(), String.join("/", UPLOAD_FILE_FOLDER, fileName));
} catch (Exception e) {
throw new BizException(EnumCode.SYSERROE, e.getMessage());
}
}
/**
* @param os response输出流
* @param filepath 文件路径
*/
private void fileDownload(OutputStream os, String filepath) throws Exception {
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(new File(filepath)));
byte[] buff = new byte[1024];
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, i);
os.flush();
i = bis.read(buff);
}
} catch (IOException e) {
throw e;
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
- ContextService
@Service
public class ContextServiceImpl implements ContextService {
/**
* 获取客户端的请求头参数
* @return map
*/
@Override
public Map<String, String> getRequestHeadersMap() {
Map<String, String> headerMap = new HashMap<>();
// 静态获取request
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//获取请求头信息
Enumeration headerNames = request.getHeaderNames();
//使用循环遍历请求头,并通过getHeader()方法获取一个指定名称的头字段
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
headerMap.put(headerName, request.getHeader(headerName));
}
return headerMap;
}
/**
* 获取客户端所有请求体参数
* @return map
*/
@Override
public Map<String, String> getRequestParamsMap() {
Map<String, String> paramMap = new HashMap<>();
// 静态获取request
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 获取请求体信息
Enumeration<String> paramter = request.getParameterNames();
while (paramter.hasMoreElements()) {
String paramName = (String) paramter.nextElement();
paramMap.put(paramName, request.getParameter(paramName));
}
return paramMap;
}
/**
* 获取request
* @return
*/
@Override
public HttpServletRequest getHttpServletRequest() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
return request;
}
@Override
public Integer getRequestLanguageType() {
Map<String, String> requestHeadersMap = getRequestHeadersMap();
String languageType = requestHeadersMap.get("language_type");
if(StringUtils.isBlank(languageType)) {
return 0;
}
return Integer.valueOf(languageType);
}
}
- UUIDStringUtil
public class UUIDStringUtil {
public static String randomUUID() {
UUID uuid = UUID.randomUUID();
return uuid.toString().replace("-", "").toUpperCase();
}
}
- application.property
# 本地或者是服务器文件存储目录
UPLOAD_FILE_FOLDER=xxxPath
# 本地或者是服务器文件存储目录 file:服务器文件路径
spring.resources.static-locations=xxxPath