spring文件下载
package com.util;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class DownloadFile {
public static ResponseEntity<byte[]> downloadResponse(String filePath, String fileName) {
try {
filePath = new String(filePath.getBytes("ISO8859-1"), "UTF-8");
if (fileName != null)
fileName = new String(fileName.getBytes("ISO8859-1"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] res = new byte[0];
File file = new File(filePath);
if (file.exists() && !file.isDirectory()) {
try {
res = FileCopyUtils.copyToByteArray(file);
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileName == null || fileName.length() == 0) {
fileName = file.getName();
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
String header = request.getHeader("User-Agent").toUpperCase();
HttpStatus status = HttpStatus.CREATED;
try {
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
fileName = fileName.replace("+", "%20");
status = HttpStatus.OK;
} else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
}
} catch (UnsupportedEncodingException ignored) {
ignored.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentLength(res.length);
return new ResponseEntity<byte[]>(res, headers, status);
}
}