小程序端
javascript
onChooseAvatar(e) {
wx.showLoading({ title: '加载中' });
const that = this;
const fs = wx.getFileSystemManager();
fs.readFile({
filePath: e.detail.avatarUrl,
encoding: 'base64',
success:(res) =>{
wx.request({
url: getApp().globalData.host + "User/UploadBase64",
method: 'POST',
//header: { 'content-type': 'application/json' },
data: {
data: res.data
},
success:(r) =>{
this.setData({ avatarUrl: getApp().globalData.url + r.data })
wx.showToast({ title: '上传成功', icon: 'none' })
},
fail(e) { console.error('base64 upload fail', e); }
});
},
fail(e) { console.error('readFile fail', e); }
});
}
服务器端
cs
[AllowAnonymous]
[HttpPost, Route("UploadBase64")]
public string UploadBase64(string data)
{
try
{
if (string.IsNullOrEmpty(data)) throw new Exception("no data");
var bytes = Convert.FromBase64String(data);
string folder = "/Uploads/image";
string save = Server.MapPath(folder);
if (!Directory.Exists(save)) Directory.CreateDirectory(save);
string file = Guid.NewGuid().ToString() + ".jpg";
string full = Path.Combine(save, file);
System.IO.File.WriteAllBytes(full, bytes);
return Path.Combine(folder, file).Replace('\\', '/');
}
catch (Exception ex)
{
return ex.Message;
}
}