微信小程序获取base64头像上传
小程序端
onChooseAvatar(e) {
const { avatarUrl } = e.detail;
this.avatarUrl = avatarUrl;
let that = this;
uni.getFileSystemManager().readFile({
filePath: that.avatarUrl,
encoding: "base64",
success(res) {
that.base64Avatar = res.data;
//将base64图片上传到服务器
that.uploadpic(that.base64Avatar);
},
fail(e) {
that.$util.Tips({
title: "头像读取失败,请稍后再试",
icon: "error",
});
},
});
}
uploadpic(base64Str) {
let that = this;
uni.request({
url: HTTP_ADMIN_URL + "/api/admin/upload/base64Image",
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: {
base64Str,
},
success: function (res) {
uni.hideLoading();
if (res.data.code === 400) {
that.$util.Tips({
title: res.data.message,
});
} else {
let data = res.data;
if (data.code === 200) {
that.avatarUrl = data.message;
that.$util.Tips({
title: "头像上传成功",
});
} else {
that.$util.Tips({
title: "头像上传失败",
});
}
}
},
fail: function (res) {
uni.hideLoading();
that.$util.Tips({
title: "上传图片失败",
});
},
});
}
服务器端
@Override
public String imageBase64Upload(String base64Str) throws IOException {
//uploadUrl = bucketName+region 比如test.oss-cn-hangzhou.aliyuncs.com
// accessKey osskey
// secretKey ossSecretKey
// storeageName bucketName
// storageRegion oss-cn-hangzhou.aliyuncs.com
OSS ossClient = new OSSClientBuilder().build(region, accessKey, secretKey);
//解码图片base64
byte[] bytesFile = Base64.decode(base64Str);
try {
// 创建PutObject请求。
InputStream inputStream = new ByteArrayInputStream(bytesFile);
String rootPath = DateUtil.nowDate(Constants.DATE_FORMAT_DATE).replace("-", "/") + "/";
String filePath = "wechat/head/"+rootPath (年/月日的文件夹);
//随机文件夹名称
String name = Uuid()+".png";
//要存到oss哪个路径,什么名称
String fileName = filePath+name;
//发起请求 bucketName就是oss创建的bucketName
ossClient.putObject(bucketName, fileName, inputStream);
//uploadUrl 就是由bucketName+region组成的路径
String url = uploadUrl + "/" + fileName;
return url;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
返回oss的图片路径,再发起微信授权的时候把这个路径保存到数据库
在用户 token没失效的时候可以使用这个路径
如果失效了得重新上传,这里不知道怎么解决好