Files
myplayer-backend/src/main/java/xin/merlin/myplayerbackend/service/UploadService.java
2025-11-27 17:42:31 +08:00

87 lines
2.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package xin.merlin.myplayerbackend.service;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.List;
@Service
@RequiredArgsConstructor
public class UploadService {
@Value("${resources.user.avatar}")
private String userAvatarDir;
@Value("${resources.group.avatar}")
private String groupAvatarDir;
@Value("${resources.playroom.avatar}")
private String playroomAvatarDir;
@Value("${resources.public}")
private String publicAvatarDir;
private static final List<String> AVATAR_ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
/**
* 上传用户、群组、放映室头像
* @param file 目标文件
* @param type 上传类型
* @param influence 受影响的id
* @return host后的访问url
* @throws IOException 抛出io异常
*/
public String uploadAvatar(MultipartFile file, Integer type,Integer influence) throws IOException {
String DIR = switch (type) {
case 1 -> userAvatarDir;
case 2 -> groupAvatarDir;
case 3 -> playroomAvatarDir;
default -> publicAvatarDir;
};
String fileName = getFilename(file, influence, DIR);
Path targetPath = Paths.get(DIR, fileName);
Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
return "/resources/user/avatar/" + fileName; // 返回访问 URL
}
/**
*
* @param file 目标文件
* @param influence 受影响的id
* @param DIR 储存的位置
* @return fileName 文件在储存之后的名字
* @throws IOException 抛出io异常
*/
private static String getFilename(MultipartFile file, Integer influence, String DIR) throws IOException {
File dir = new File(DIR);
if (!dir.exists()) dir.mkdirs();
// 取文件扩展名并检查是否合法
String originalFileName = file.getOriginalFilename();
String fileExtension = "";
if (originalFileName != null && originalFileName.contains(".")) {
fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
}
if (!AVATAR_ALLOWED_EXTENSIONS.contains(fileExtension)) {
throw new IOException("仅支持 JPG, PNG, GIF 格式");
}
// 以id进行命名方便直接替换
return influence.toString() + fileExtension;
}
}