前端代码
let base64Data = "图片base64数据";
const formData = new FormData();
formData.append("biz", 'person');
formData.append("base64", base64Data);
let url = config.configData.api_url + "/business/common/upByBase64";
httpFile(url,formData).then((res) => {
resolve(res);
})
httpFile函数
function httpFile (path = '', formData = {}) {
let token = sessionStorage.getItem("token");
return new Promise(function (resolve, reject) {
axios.post(path + "/", formData, {headers: {"token": token}, "Content-type":"multipart/form-data",timeout:120000})
.then(function (response) {
check(response.data);
resolve(response)
})
.catch(function (error) {
reject(error)
})
})
}
后端代码
@PostMapping(value = "/upByBase64")
public Result<?> upByBase64(HttpServletRequest request, HttpServletResponse response) {
Result<?> result = new Result<>();
String savePath = "";
String biz = "";
if(StringUtils.isNotEmpty(request.getParameter("biz"))){
biz = request.getParameter("biz");
}else{
biz = "other";
}
String base64str = request.getParameter("base64");
if (base64str.contains("data:image")) {
base64str = base64str.substring(base64str.indexOf(",") + 1);
}
base64str = base64str.replace("\r\n", "");
InputStream inputStream=null;
OutputStream outputStream = null;
try {
// 从inputStream读取数据
byte[] bytes = Base64.getDecoder().decode(base64str);
inputStream = new ByteArrayInputStream(bytes);
String newFile = UUID.randomUUID().toString().replace("-", "") + ".png";
savePath = biz + File.separator + newFile;
// 创建本地文件输出流
outputStream = new FileOutputStream(uploadpath + File.separator + savePath );
byte[] buffer = new byte[1024];
int bytesRead;
// 将数据从inputStream写入outputStream
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("文件转存成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭输入流和输出流
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return Result.ok(savePath);
}