文件工具类FileUtils
public class FileUtils{
public static void setAttaResHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.setHeader("Content-disposition", contentDispositionValue.toString());
}
public static String percentEncode(String str) throws UnsupportedEncodingException {
String encode = URLEncoder.encode(str, StandardCharsets.UTF_8.toString());
return encode.replaceAll("\\+", "%20");
}
private final String getCodeFileName(MultipartFile file) {
String suffix = getExtension(file);
Date date = new Date();
String fileName = DateFormatUtils.format(date, "yyyy/MM/dd") + "/" + IdUtils.fastUUID() + "." + suffix;
return fileName;
}
private final String getPathFileName(String uploadDir, String fileName) throws IOException {
int dirLastIndex = sysConfig.getProfile().length() + 1;
String currDir = uploadDir.substring(dirLastIndex);
String pathFileName = Constants.RESOURCE_PREFIX + "/" + currDir + "/" + fileName;
return pathFileName;
}
private final File getAbsoluteFile(String uploadDir, String fileName) throws IOException {
File desc = new File(uploadDir + File.separator + fileName);
if (!desc.exists()) {
if (!desc.getParentFile().exists()) {
desc.getParentFile().mkdirs();
}
}
return desc;
}
public String upload(String baseDir, MultipartFile file) throws IOException {
String fileName = getCodeFileName(file);
File desc = getAbsoluteFile(baseDir, fileName);
file.transferTo(desc);
return getPathFileName(baseDir, fileName);
}
public static void writeBytes(String filePath, OutputStream os) throws IOException {
FileInputStream fis = null;
try {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0) {
os.write(b, 0, length);
}
} catch (IOException e) {
throw e;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
服务配置类ServerConfig
@Component
public class ServerConfig {
public String getUrl() {
HttpServletRequest request = ServletUtils.getRequest();
StringBuffer url = request.getRequestURL();
String contextPath = request.getServletContext().getContextPath();
return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
}
}
客户端工具类ServletUtils
public class ServletUtils {
public static ServletRequestAttributes getRequestAttributes() {
RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
return (ServletRequestAttributes) attributes;
}
public static HttpServletRequest getRequest() {
return getRequestAttributes().getRequest();
}
返回状态类 Result
public class Result extends HashMap<String, Object> {
public static final String CODE_TAG = "code";
public static final String MSG_TAG = "msg";
public static final String DATA_TAG = "data";
public Result() {
}
public Result(int code, String msg) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
public Result(int code, String msg, Object data) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data)) {
super.put(DATA_TAG, data);
}
}
public static Result success() {
return Result.success("操作成功");
}
public static Result success(Object data) {
return Result.success("操作成功", data);
}
public static Result success(String msg) {
return Result.success(msg, null);
}
public static Result success(String msg, Object data) {
return new Result(200, msg, data);
}
public static Result error() {
return Result.error("操作失败");
}
public static Result error(String msg) {
return Result.error(msg, null);
}
public static Result error(String msg, Object data) {
return new Result(500, msg, data);
}
public static Result error(int code, String msg) {
return new Result(code, msg, null);
}
}
资源请求类ResourceReqController
@RestController
public class ResourceReqController{
private static final Logger log = LoggerFactory.getLogger(ResourceReqController.class);
@Autowired
private ServerConfig serverConfig;
@GetMapping("/common/download")
public void fileDownload(String fileName, HttpServletResponse response, HttpServletRequest request) {
try {
String realFileName = System.currentTimeMillis() + fileName;
String filePath = sysConfig.getDownloadPath() + fileName;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttaResHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
@PostMapping("/common/upload")
public Result uploadFile(MultipartFile file) throws Exception {
try {
String filePath = sysConfig.getUploadPath();
String fileName = FileUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
Result res = Result.success();
res.put("fileName", fileName);
res.put("url", url);
return res;
} catch (Exception e) {
return Result.error(e.getMessage());
}
}
}