Controller
package com.xgqc.controller;
import com.xgqc.entity.PicUpload;
import com.xgqc.result.Result;
import com.xgqc.service.Impl.FileUploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Map;
/**
* @author cxy
* @create 2024-07-18 08:43:55
*/
@Slf4j
@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = "*")
@RequiredArgsConstructor
@Tag(name = "上传图片")
public class FileUploadController {
// 允许上传的格式 图片形式
private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png"};
@Resource
private FileUploadService fileUploadService;
@PostMapping("/uploadImg")
@Operation(summary = "上传单个图片")
public Result uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
boolean isFlag = false;
//遍历判断是否是允许上传的格式
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
isFlag = true;
break;
}
}
if (isFlag) {
PicUpload picUploadResult = fileUploadService.uplodadImg(file, request);
boolean isLegal = picUploadResult.isLegal();
if (isLegal) {
Map resMap = new HashMap<>();
resMap.put("imgUrl", picUploadResult.getImgPath());
resMap.put("base64", picUploadResult.getBase64());
return Result.success(resMap);
} else {
return Result.error("图片上传有误");
}
} else {
return Result.error("上传的图片格式必须为:bmp,jpg,jpeg,png");
}
}
@PostMapping("/uploadManyImg")
@Operation(summary = "上传多个图片")
public Result uploadManyImg(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
boolean isFlag = false;
for (MultipartFile uploadFile : files) {
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
isFlag = true;
break;
}
}
}
if (isFlag) {
PicUpload picUploadResult = fileUploadService.uploadManyImg(files, request);
boolean isLegal = picUploadResult.isLegal();
if (isLegal) {
Map resMap = new HashMap<>();
resMap.put("imgPaths", picUploadResult.getImgPahts());
return Result.success(resMap);
} else {
return Result.error("图片上传有误");
}
} else {
return Result.error("上传的图片格式必须为:bmp,jpg,jpeg,png");
}
}
}
service
package com.xgqc.service.Impl;
import com.xgqc.entity.PicUpload;
import com.xgqc.utils.Base64Util;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author cxy
* @create 2024-07-18 08:41:57
*/
@Service
public class FileUploadService {
// 项目上传至绝对路径(在yml里配置你的项目绝对路径)
//@Value("${file.save-path}")
private String baseFilePath = "D:\\working-item\\cxy后端\\image";
// 项目根路径下的目录 -- SpringBoot static 目录相当于是根路径下(SpringBoot 默认)
private final static String UPLOAD_PATH_PREFIX = "statics/uploadFile/";
//图片存储路径是baseFilePath+UPLOAD_PATH_PREFIX
/**
* 上传图片方法类
*
* @param multipartFile
* @param request
* @return
*/
private PicUpload uploadImgMethod(MultipartFile multipartFile, HttpServletRequest request) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd/");
String format = sdf.format(new Date());
//存放上传文件的文件夹
File file = new File(baseFilePath + format);
PicUpload picUploadResult = new PicUpload();
if (multipartFile.isEmpty()) {
//返回选择文件提示
picUploadResult.setLegal(false);
return picUploadResult;
}
if (!file.isDirectory()) {
//递归生成文件夹
file.mkdirs();
}
//获取原始的名字 original:最初的,起始的 方法是得到原来的文件名在客户机的文件系统名称
String oldName = multipartFile.getOriginalFilename();
//创建新名字
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
//构建真实的文件路径
File newFile = new File(file.getAbsolutePath() + File.separator + newName);
//转存文件到指定路径,如果文件名重复的话,将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
multipartFile.transferTo(newFile);
String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/picbook/" + UPLOAD_PATH_PREFIX + format + newName;
picUploadResult.setLegal(true);
picUploadResult.setImgPath(filePath);
String base64 = Base64Util.base64Encoding(newName, file.getAbsolutePath());
picUploadResult.setBase64(base64);
return picUploadResult;
} catch (Exception e) {
e.printStackTrace();
}
picUploadResult.setLegal(false);
return picUploadResult;
}
public PicUpload uplodadImg(MultipartFile file, HttpServletRequest request) {
return uploadImgMethod(file, request);
}
public PicUpload uploadManyImg(MultipartFile[] uploadFile, HttpServletRequest request) {
List<String> imgPaths = new ArrayList<>();
for (MultipartFile multipartFile : uploadFile) {
PicUpload picUploadResult = uploadImgMethod(multipartFile, request);
if (picUploadResult.isLegal()) {
imgPaths.add(picUploadResult.getImgPath());
} else {
return picUploadResult;
}
}
PicUpload picUploadResult = new PicUpload();
picUploadResult.setLegal(true);
picUploadResult.setImgPahts(imgPaths);
return picUploadResult;
}
}
工具类
package com.xgqc.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
/**
* @author cxy
* @create 2024-07-18 09:09:01
*/
public class Base64Util {
// base64图片 存储的byte数组
private static byte[] baseByte = new byte[0];
public static String base64Encoding(String file, String path) {
String base64 = "";
try {
// 从本地目录下获取图片
File file1 = new File(path + "/" + file);
// base64图片前缀
String pre = "data:image/jpg;base64,";
// 读取图片
FileInputStream fileInputStream = new FileInputStream(file1);
// 读取字节长度
int len = 0;
// baseByte数组的容量
int capacity = 0;
byte[] bytes = new byte[1024];
while ((len = fileInputStream.read(bytes)) != -1) {
// 对原数组进行拷贝扩容
baseByte = Arrays.copyOf(baseByte, len + capacity);
// 将新数据拷贝到新扩容的数组
System.arraycopy(bytes, 0, baseByte, capacity, len);
// 数据容量增加
capacity += len;
}
// 获取base64编码器
Base64.Encoder encoder = Base64.getEncoder();
// 将字节数组转换base64
base64 = pre + encoder.encodeToString(baseByte);
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return base64;
}
}
记得数据库存储字段大小改一下
进入本地命令cmd
net start mysql
mysql -u root -p
输入密码回车登入MySQL服务器
show variables like 'max_allowed_packet'; //查看max_allowed_packet大小
set global max_allowed_packet=10*1024*1024; //设置允许的最大数据包大小,单位为B
exit; //退出MySQL服务器