后端添加显示默认头像或图片

Signed-off-by: zup <jiu3295282258@163.com>
main
laptop_zup 9 months ago committed by zup
parent 9e54e14587
commit 3c9cd07a5a

@ -2,9 +2,12 @@ package com.yeqifu.sys.controller;
import cn.hutool.core.date.DateUtil;
import com.yeqifu.sys.common.AppFileUtils;
import com.yeqifu.sys.common.Constast;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpStatus;
@ -28,8 +31,8 @@ public class FileController {
/**
*
* @param mf
* @return
* @param mf
* @return
*/
@RequestMapping("uploadImage")
public Map<String, Object> uploadImage(MultipartFile mf) {
@ -57,7 +60,7 @@ public class FileController {
// 得到当前日期的字符串
String dirName = DateUtil.format(new Date(), "yyyy-MM-dd");
// 构造文件夹
// 构造文件夹路径
File dirFile = new File(AppFileUtils.UPLOAD_PATH, dirName);
// 判断当前文件夹是否存在
@ -87,14 +90,18 @@ public class FileController {
return map;
}
/**
*
* @param path
* return
* @return
*/
@RequestMapping("showImageByPath")
public ResponseEntity<byte[]> downloadImage(String path) {
public ResponseEntity<byte[]> downloadImage(@RequestParam String path) {
// 如果是默认图片,直接返回
if (path.equals(Constast.DEFAULT_IMG_USER) || path.equals(Constast.DEFAULT_IMG_GOODS)) {
return getDefaultImage(path);
}
// 规范路径,防止路径穿越
Path normalizedPath = Paths.get(AppFileUtils.UPLOAD_PATH, path).normalize();
@ -102,7 +109,6 @@ public class FileController {
if (!normalizedPath.startsWith(AppFileUtils.UPLOAD_PATH)) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); // 如果路径越界返回403 Forbidden
}
// 检查文件是否存在
File file = normalizedPath.toFile();
if (!file.exists() || !file.isFile()) {
@ -131,4 +137,21 @@ public class FileController {
}
}
/**
*
*/
private ResponseEntity<byte[]> getDefaultImage(String path) {
// 返回一个 302 重定向响应,重定向到默认图片的 URL
if (path.equals(Constast.DEFAULT_IMG_USER)) {
return ResponseEntity.status(HttpStatus.FOUND)
.header(HttpHeaders.LOCATION, Constast.DEFAULT_IMG_USER) // 图片的 URL 路径
.build();
} else if (path.equals(Constast.DEFAULT_IMG_GOODS)) {
return ResponseEntity.status(HttpStatus.FOUND)
.header(HttpHeaders.LOCATION, Constast.DEFAULT_IMG_GOODS) // 图片的 URL 路径
.build();
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
}

Loading…
Cancel
Save