前言
今天在做项目时发现,前端使用element组件时,上传图片为了与其他信息一起提交,先阻拦了图片的提交,再把图片的base64编码信息发了过来,但我使用MultipartFile接受不到,好像是他请求头不对的原因,但他不会解决,所以我只能用string保存他的图片信息,在后端自己转换格式,下面是我遇到的几个坑
一、代码
1.1 将图片保存到服务器某个文件夹下,并返回url地址
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Base64;
import java.util.UUID;
@Slf4j
@Component
public class UploadUtil {
@Value("${util.targetFilePath}")
private String targetFile;
public String upload(String file) {
String fileName="./img/"+UUID.randomUUID()+".jpg";//图片名
file = file.replaceAll(" ","+");
String filePath=targetFile;
filePath=filePath+fileName;
if (file == null && filePath == null) {
return "数据为空";
}
try {
Files.write(Paths.get(filePath), Base64.getDecoder().decode(file), StandardOpenOption.CREATE);
return fileName;
} catch (IOException e) {
e.printStackTrace();
return "文件创建失败";
}
}
}
配置文件代码:
##静态资源默认查找位置
spring.resources.static-locations=file:/home/weblogic/upload/
## 文件存储位置
util.targetFilePath=/home/weblogic/upload/
1.2 service层调用,并将返回的url保存到数据库中
@Autowired
UploadUtil uploadUtil;
//上传接口一——创建小说
@Override
public ServerResponse NovelInformation_Create(NovelInformation novelInformation, String file) {
String url=null;
url= uploadUtil.upload(file);
novelInformation.setNovel_photo(url);
Date date = new Date();
novelInformation.setCreate_date(date);
uploadMapper.insert_NovelInformation(novelInformation);
return ServerResponse.createBySuccessMessage("小说创建成功");
}
1.3 坑一:自己测试时用的url栏发的信息,报错url内容过长
解决办法:application.properties添加内容
##修改接受url长度
server.max-http-header-size=102400
1.4 坑二:自己测试时发现,url中的+会自动变为空格
解决办法:将空格变为+
file = file.replaceAll(" ","+");