工具类
package com.muyi.psi.rest.modular.auth.util;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
/**
* @Author: AppleSugar
* @Description:base64解析类
* @Date: Created in 19:14 2020/6/11
* @Modified By:
*/
public class BASE64DecodedMultipartFile implements MultipartFile{
private final byte[] imgContent;
private final String header;
public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length == 0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File dest) throws IOException, IllegalStateException {
new FileOutputStream(dest).write(imgContent);
}
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
BASE64Decoder decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
base64 是公共接口 先调用公共的上传图片接口! 然后前端回显存入服务器的图片URL , 在把URL从添加的接口 添加数据库里!
/**
* base64接受图片
* @param base
* @param request
* @return
*/
@PostMapping("/base64")
@ResponseBody
public Object base(String base,HttpServletRequest request){
MultipartFile file= BASE64DecodedMultipartFile.base64ToMultipart(base);
String url = uploadFile(request, file);
return url;
}
// //上传文件
// @PostMapping("/multipart")
// @ResponseBody
public String uploadFile(HttpServletRequest request, MultipartFile mediaFile) {
String result = "false";
if (!mediaFile.isEmpty()&&!mediaFile.getOriginalFilename().equals("null")) {
File targetFile = null;
String url = "";//返回存储路径
String fileName = mediaFile.getOriginalFilename();
if (fileName != null && fileName != "") {
String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + fileF;//新的文件名
//先判断文件是否存在
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String fileAdd = sdf.format(new Date());
//获取文件夹路径
File file1 = new File(path + "/" + fileAdd);
//如果文件夹不存在则创建
if (!file1.exists() && !file1.isDirectory()) {
file1.mkdirs();
}
//将图片存入文件夹
targetFile = new File(file1, fileName);
try {
//将上传的文件写到服务器上指定的文件。
mediaFile.transferTo(targetFile);
url = returnUrl + fileAdd + "/" + fileName;
return url;
} catch (Exception e) {
e.printStackTrace();
return "false";
}
}
}
return result;
}
这个是前端调用的请求方式
imglist_msg(e){
console.log(e)
uni.request({
url: 'https://xxx.com/base64', //仅为示例,并非真实接口地址。
data: {
base: e[0]
},
method:'POST',
header: {
'Content-Type': "application/x-www-form-urlencoded", //自定义请求头信息
},
success: (res) => {
console.log(res);
// this.text = 'request success';
}
});
},
如果前端传的图片值是base64加密的 就需要后台方法接收 解密
/**
* Base64解密
*/
private static String decodeBase64(String str) throws UnsupportedEncodingException {
byte[] decoded = Base64.getDecoder().decode(str);
String decodeStr = new String(decoded);
return URLDecoder.decode(decodeStr,"utf-8");
}