背景
在uniapp实现微信小程序登陆过程中, 我们提供了用户获取自己的头像功能。 但是微信获取的头像都是临时路径。
需要我们进行转换并上传。
本文记录从前后端如何完成这个头像获取,上传到服务器的过程。
//这个就是微信的临时头像路径
wxfile://tmp_7ed9bdc04c06492467367ab021d68d46.jpg
uniapp代码
- template页面
<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
<image class="avatar" :src="defaultAvatar" mode="aspectFit"></image>
<input name="avatar" :value="defaultAvatar" style="display: none;"/>
</button>
- script代码
onChooseAvatar(e) {
console.log('微信头像信息', e)
// 将数据赋值
const { avatarUrl } = e.detail
let tmpFilePath = avatarUrl;
// this.defaultAvatar = avatarUrl
//对临时图片链接进行base64编码
var avatarUrl_base64 = 'data:image/jpeg;base64,' + wx.getFileSystemManager().readFileSync(tmpFilePath, 'base64')
var reqData = {
"base64Str": avatarUrl_base64
}
this.http.post(this.$url.file.uploadBase64Img, {data: reqData, showLoading: false}).then(res => {
if(res.code === 200){
this.defaultAvatar = res.data;
} else{
this.tui.toast(res.message);
}
}).catch(e => {
console.log(e)
})
},
boot端代码
- controller层
@ApiOperation(value = "上传base64格式文件", notes = "上传base64格式文件")
@PostMapping("uploadBase64Img")
public Result<?> uploadBase64Img(@RequestBody Base64Req base64Req) {
ValidatorUtils.validateEntity(base64Req);
return Results.newSuccessResult(fileService.uploadBase64(base64Req.getBase64Str()));
}
- service层
@Override
public String uploadBase64(String base64Str) {
MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64Str);
return Optional.ofNullable(uploadFileToOSS(multipartFile)).map(m->m.replace("https://markkkkdkd.oss-cn-beijing.aliyuncs.com", "http://cdn.zengzhang.vip")).orElse("http://cdn.zengzhang.vip/test/avatar/avatar27.png");
}
- BASE64DecodedMultipartFile
package com.milu.boss.common.util;
/**
* base64转multipartfile工具类
* @author qzz
*/
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import java.io.*;
/**
* base64转MultipartFile
*/
public class BASE64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
/**
*
* @param imgContent
* @param 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 转 MultipartFile,获取对应的InputStream
* @param base64
* @return
*/
public static InputStream getQrCodeInputStream(String base64){
MultipartFile multipartFile = BASE64DecodedMultipartFile.base64ToMultipart(base64);
try {
return multipartFile.getInputStream();
} catch (IOException e) {
return null;
}
}
}
最终演示
这是作者新开发的打牌记账小程序, 希望您多多支持, 多多推荐。