Skip to content

Commit

Permalink
🎨 规范文件上传参数
Browse files Browse the repository at this point in the history
  • Loading branch information
ronger-x committed Mar 6, 2024
1 parent a9ecf0c commit 52d2ebb
Show file tree
Hide file tree
Showing 8 changed files with 99 additions and 76 deletions.
14 changes: 14 additions & 0 deletions src/main/java/com/rymcu/forest/enumerate/FileDataType.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.rymcu.forest.enumerate;

/**
* Created on 2024/3/6 10:07.
*
* @author ronger
* @email [email protected]
* @desc : com.rymcu.forest.enumerate
*/
public class FileDataType {
public final static String URL = "0";
public final static String BASE64 = "1";

}
38 changes: 38 additions & 0 deletions src/main/java/com/rymcu/forest/enumerate/FilePath.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.rymcu.forest.enumerate;

import java.util.Arrays;

/**
* Created on 2024/3/6 10:51.
*
* @author ronger
* @email [email protected]
* @desc : com.rymcu.forest.enumerate
*/
public enum FilePath {
AVATAR,
ARTICLE,
TAG,
TOPIC,
PORTFOLIO,
PRODUCT,
IMAGES;

public static FilePath getFilePath(int type) {
for (FilePath filePath : FilePath.values()) {
if (filePath.ordinal() == type) {
return filePath;
}
}
return FilePath.IMAGES;
}

public static String getPath(int type) {
for (FilePath filePath : FilePath.values()) {
if (filePath.ordinal() == type) {
return filePath.name().toLowerCase();
}
}
return FilePath.IMAGES.name().toLowerCase();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import com.rymcu.forest.core.service.AbstractService;
import com.rymcu.forest.dto.*;
import com.rymcu.forest.entity.Portfolio;
import com.rymcu.forest.enumerate.FilePath;
import com.rymcu.forest.enumerate.FileDataType;
import com.rymcu.forest.lucene.model.PortfolioLucene;
import com.rymcu.forest.lucene.util.PortfolioIndexUtil;
import com.rymcu.forest.mapper.PortfolioMapper;
Expand All @@ -16,7 +18,6 @@
import com.rymcu.forest.service.UserService;
import com.rymcu.forest.util.XssUtils;
import com.rymcu.forest.web.api.common.UploadController;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
Expand Down Expand Up @@ -63,8 +64,8 @@ public PortfolioDTO findPortfolioDTOById(Long idPortfolio, Integer type) {

@Override
public Portfolio postPortfolio(Portfolio portfolio) {
if (StringUtils.isNotBlank(portfolio.getHeadImgType())) {
String headImgUrl = UploadController.uploadBase64File(portfolio.getHeadImgUrl(), 0);
if (FileDataType.BASE64.equals(portfolio.getHeadImgType())) {
String headImgUrl = UploadController.uploadBase64File(portfolio.getHeadImgUrl(), FilePath.PORTFOLIO);
portfolio.setHeadImgUrl(headImgUrl);
}
if (portfolio.getIdPortfolio() == null || portfolio.getIdPortfolio() == 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@
import com.rymcu.forest.core.service.AbstractService;
import com.rymcu.forest.dto.ProductDTO;
import com.rymcu.forest.entity.Product;
import com.rymcu.forest.enumerate.FilePath;
import com.rymcu.forest.enumerate.FileDataType;
import com.rymcu.forest.mapper.ProductMapper;
import com.rymcu.forest.service.ProductService;
import com.rymcu.forest.util.BeanCopierUtil;
import com.rymcu.forest.web.api.common.UploadController;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
Expand Down Expand Up @@ -49,8 +50,8 @@ public List<ProductDTO> findOnlineProducts() {
@Override
public Product postProduct(ProductDTO product) {
boolean isUpdate = product.getIdProduct() > 0;
if (StringUtils.isNotBlank(product.getProductImgType())) {
String headImgUrl = UploadController.uploadBase64File(product.getProductImgUrl(), 0);
if (FileDataType.BASE64.equals(product.getProductImgType())) {
String headImgUrl = UploadController.uploadBase64File(product.getProductImgUrl(), FilePath.PRODUCT);
product.setProductImgUrl(headImgUrl);
}
Product newProduct;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.rymcu.forest.dto.LabelModel;
import com.rymcu.forest.entity.Article;
import com.rymcu.forest.entity.Tag;
import com.rymcu.forest.enumerate.FilePath;
import com.rymcu.forest.mapper.ArticleMapper;
import com.rymcu.forest.mapper.TagMapper;
import com.rymcu.forest.service.TagService;
Expand Down Expand Up @@ -126,7 +127,7 @@ public Tag saveTag(Tag tag) {
}
}
if (StringUtils.isNotBlank(tag.getTagIconPath()) && tag.getTagIconPath().contains("base64")) {
String tagIconPath = UploadController.uploadBase64File(tag.getTagIconPath(), 2);
String tagIconPath = UploadController.uploadBase64File(tag.getTagIconPath(), FilePath.TAG);
tag.setTagIconPath(tagIconPath);
} else {
tag.setTagIconPath(tag.getTagIconPath());
Expand All @@ -137,7 +138,7 @@ public Tag saveTag(Tag tag) {
} else {
tag.setUpdatedTime(new Date());
if (StringUtils.isNotBlank(tag.getTagIconPath()) && tag.getTagIconPath().contains("base64")) {
String tagIconPath = UploadController.uploadBase64File(tag.getTagIconPath(), 2);
String tagIconPath = UploadController.uploadBase64File(tag.getTagIconPath(), FilePath.TAG);
tag.setTagIconPath(tagIconPath);
}
result = tagMapper.update(tag.getIdTag(), tag.getTagUri(), tag.getTagIconPath(), tag.getTagStatus(), tag.getTagDescription(), tag.getTagReservation());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import com.rymcu.forest.dto.admin.TopicTagDTO;
import com.rymcu.forest.entity.Tag;
import com.rymcu.forest.entity.Topic;
import com.rymcu.forest.enumerate.FilePath;
import com.rymcu.forest.mapper.TopicMapper;
import com.rymcu.forest.service.TopicService;
import com.rymcu.forest.util.XssUtils;
Expand Down Expand Up @@ -59,7 +60,7 @@ public Topic saveTopic(Topic topic) throws ServiceException {
}
}
if (StringUtils.isNotBlank(topic.getTopicIconPath()) && topic.getTopicIconPath().contains("base64")) {
String topicIconPath = UploadController.uploadBase64File(topic.getTopicIconPath(), 3);
String topicIconPath = UploadController.uploadBase64File(topic.getTopicIconPath(), FilePath.TOPIC);
topic.setTopicIconPath(topicIconPath);
} else {
topic.setTopicIconPath(topic.getTopicIconPath());
Expand All @@ -74,7 +75,7 @@ public Topic saveTopic(Topic topic) throws ServiceException {
result = topicMapper.insertSelective(topic);
} else {
if (StringUtils.isNotBlank(topic.getTopicIconPath()) && topic.getTopicIconPath().contains("base64")) {
String topicIconPath = UploadController.uploadBase64File(topic.getTopicIconPath(), 3);
String topicIconPath = UploadController.uploadBase64File(topic.getTopicIconPath(), FilePath.TOPIC);
topic.setTopicIconPath(topicIconPath);
}
topic.setUpdatedTime(new Date());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import com.rymcu.forest.entity.Role;
import com.rymcu.forest.entity.User;
import com.rymcu.forest.entity.UserExtend;
import com.rymcu.forest.enumerate.FilePath;
import com.rymcu.forest.enumerate.FileDataType;
import com.rymcu.forest.lucene.model.UserLucene;
import com.rymcu.forest.lucene.util.UserIndexUtil;
import com.rymcu.forest.mapper.RoleMapper;
Expand Down Expand Up @@ -191,8 +193,8 @@ public UserInfoDTO updateUserInfo(UserInfoDTO user) throws ServiceException {
if (number > 0) {
throw new NicknameOccupyException("该昵称已使用!");
}
if (StringUtils.isNotBlank(user.getAvatarType()) && AVATAR_SVG_TYPE.equals(user.getAvatarType())) {
String avatarUrl = UploadController.uploadBase64File(user.getAvatarUrl(), 0);
if (FileDataType.BASE64.equals(user.getAvatarType())) {
String avatarUrl = UploadController.uploadBase64File(user.getAvatarUrl(), FilePath.AVATAR);
user.setAvatarUrl(avatarUrl);
user.setAvatarType("0");
}
Expand Down
93 changes: 29 additions & 64 deletions src/main/java/com/rymcu/forest/web/api/common/UploadController.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.rymcu.forest.core.result.GlobalResultGenerator;
import com.rymcu.forest.dto.LinkToImageUrlDTO;
import com.rymcu.forest.dto.TokenUser;
import com.rymcu.forest.enumerate.FilePath;
import com.rymcu.forest.service.ForestFileService;
import com.rymcu.forest.util.FileUtils;
import com.rymcu.forest.util.SpringContextHolder;
Expand All @@ -29,6 +30,7 @@
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import com.rymcu.forest.util.SSRFUtil;

/**
Expand All @@ -48,38 +50,18 @@ public class UploadController {
@Resource
private ForestFileService forestFileService;

private static String getTypePath(Integer type) {
String typePath;
switch (type) {
case 0:
typePath = "avatar";
break;
case 1:
typePath = "article";
break;
case 2:
typePath = "tag";
break;
case 3:
typePath = "topic";
break;
default:
typePath = "images";
}
return typePath;
}

public static String uploadBase64File(String fileStr, Integer type) {
public static String uploadBase64File(String fileStr, FilePath filePath) {
if (StringUtils.isBlank(fileStr)) {
return "";
}
String typePath = getTypePath(type);
String typePath = filePath.name().toLowerCase();
//图片存储路径
String ctxHeadPicPath = env.getProperty("resource.pic-path");
String dir = ctxHeadPicPath + "/" + typePath;
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
// 创建文件根目录
file.mkdirs();
}

String localPath = Utils.getProperty("resource.file-path") + "/" + typePath + "/";
Expand All @@ -98,9 +80,9 @@ public static String uploadBase64File(String fileStr, Integer type) {
/**
* 从输入流中获取字节数组
*
* @param inputStream
* @return
* @throws IOException
* @param inputStream 输入流
* @return byte[]
* @throws IOException IO 异常
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
Expand Down Expand Up @@ -134,20 +116,10 @@ public GlobalResult<JSONObject> uploadPicture(@RequestParam(value = "file", requ
data.put("url", fileUrl);
return GlobalResultGenerator.genSuccessResult(data);
}
String typePath = getTypePath(type);
//图片存储路径
String ctxHeadPicPath = env.getProperty("resource.pic-path");
String dir = ctxHeadPicPath + "/" + typePath;
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}

File file = genFile(type);
String typePath = FilePath.getPath(type);
String localPath = Utils.getProperty("resource.file-path") + "/" + typePath + "/";


String fileName = System.currentTimeMillis() + fileType;

String savePath = file.getPath() + File.separator + fileName;
fileUrl = localPath + fileName;
File saveFile = new File(savePath);
Expand All @@ -162,25 +134,29 @@ public GlobalResult<JSONObject> uploadPicture(@RequestParam(value = "file", requ

}

@PostMapping("/file/batch")
@Transactional(rollbackFor = Exception.class)
public GlobalResult<JSONObject> batchFileUpload(@RequestParam(value = "file[]", required = false) MultipartFile[] multipartFiles, @RequestParam(defaultValue = "1") Integer type, HttpServletRequest request) {
TokenUser tokenUser = getTokenUser(request);
String typePath = getTypePath(type);
private File genFile(Integer type) {
String typePath = FilePath.getPath(type);
//图片存储路径
String ctxHeadPicPath = env.getProperty("resource.pic-path");
String dir = ctxHeadPicPath + "/" + typePath;
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
return file;
}

@PostMapping("/file/batch")
@Transactional(rollbackFor = Exception.class)
public GlobalResult<JSONObject> batchFileUpload(@RequestParam(value = "file[]", required = false) MultipartFile[] multipartFiles, @RequestParam(defaultValue = "1") Integer type, HttpServletRequest request) {
TokenUser tokenUser = getTokenUser(request);
File file = genFile(type);
String typePath = FilePath.getPath(type);
String localPath = Utils.getProperty("resource.file-path") + "/" + typePath + "/";
Map successMap = new HashMap(16);
Set errFiles = new HashSet();
Map<String, String> successMap = new HashMap<>(16);
Set<String> errFiles = new HashSet<>();

for (int i = 0, len = multipartFiles.length; i < len; i++) {
MultipartFile multipartFile = multipartFiles[i];
for (MultipartFile multipartFile : multipartFiles) {
String orgName = multipartFile.getOriginalFilename();

if (multipartFile.getSize() == 0) {
Expand Down Expand Up @@ -247,12 +223,10 @@ private GlobalResult<JSONObject> getUploadToken(HttpServletRequest request, Stri

@PostMapping("/file/link")
@Transactional(rollbackFor = Exception.class)
public GlobalResult linkToImageUrl(@RequestBody LinkToImageUrlDTO linkToImageUrlDTO, HttpServletRequest request) throws IOException {

public GlobalResult<Map<String, String>> linkToImageUrl(@RequestBody LinkToImageUrlDTO linkToImageUrlDTO, HttpServletRequest request) throws IOException {
TokenUser tokenUser = getTokenUser(request);
String url = linkToImageUrlDTO.getUrl();
Map data = new HashMap(2);

Map<String, String> data = new HashMap<>(2);
if (StringUtils.isBlank(url)) {
data.put("message", "文件为空!");
return GlobalResultGenerator.genSuccessResult(data);
Expand Down Expand Up @@ -293,19 +267,12 @@ public GlobalResult linkToImageUrl(@RequestBody LinkToImageUrlDTO linkToImageUrl
data.put("url", fileUrl);
return GlobalResultGenerator.genSuccessResult(data);
}

Integer type = linkToImageUrlDTO.getType();
if (Objects.isNull(type)) {
type = 1;
}
String typePath = getTypePath(type);
//图片存储路径
String ctxHeadPicPath = env.getProperty("resource.pic-path");
String dir = ctxHeadPicPath + "/" + typePath;
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
File file = genFile(type);
String typePath = FilePath.getPath(type);
String fileName = System.currentTimeMillis() + fileType;
fileUrl = Utils.getProperty("resource.file-path") + "/" + typePath + "/" + fileName;

Expand All @@ -318,9 +285,7 @@ public GlobalResult linkToImageUrl(@RequestBody LinkToImageUrlDTO linkToImageUrl
data.put("url", fileUrl);
return GlobalResultGenerator.genSuccessResult(data);
} catch (IOException e) {
/**
* 上传失败返回原链接
*/
// 上传失败返回原链接
logger.error("link: {},\nmessage: {}", url, e.getMessage());
data.put("originalURL", url);
data.put("url", url);
Expand Down

0 comments on commit 52d2ebb

Please sign in to comment.