前台接口上传图片时传输二进制流 变为我们想要的图片 进行以下总结
话不多少,进入正题
1、前台页面代码(小程序代码)
changeimg: function() {
var token = wx.getStorageSync('token') || [];
let that = this wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success(res) {
const tempFilePath = res.tempFilePaths[0] that.base64({
url: tempFilePath,
type: 'jpeg'
}).then(res = >{
console.log(res) //res是base64路径
var token = wx.getStorageSync('token') || [];
var user = {
"route": "renyuan/",
"url11": res,
"name1": "a.jpeg"
}
wx.request({
url: serverUrl + '/loginUploadPicture', // 接口路径
method: "POST",
data: user,
success(res) {
console.log(res.data.scrl) var pi_path = res.data.scrl;
var u_id = wx.getStorageSync('uid') || [];
var picture = {
"pi_path": pi_path,
"u_id": u_id
}
wx.request({
url: serverUrl + '/pictureUpDate',
method: "POST",
data: picture,
header: {
'token': token
},
success(res) {
wx.showToast({
title: "修改成功",
icon: 'success',
duration: 1000
});
setTimeout(function() {
wx.switchTab({
url: '/pages/mine/mine'
})
},
1000)
},
fail(res) {
wx.showToast({
title: '请求错误',
image: '../../images/cuowu.png',
duration: 1000
})
}
})
},
fail(res) {
wx.showToast({
title: '请求错误',
image: '../../images/cuowu.png',
duration: 1000
})
}
})
})
}
})
},
base64({
url,
type
}) {
return new Promise((resolve, reject) = >{
wx.getFileSystemManager().readFile({
filePath: url,
//选择图片返回的相对路径
encoding: 'base64',
//编码格式
success: res = >{
resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
},
fail: res = >reject(res.errMsg)
})
})
},
2、PHP后台方法
/*
* 执行上传文件写入文件
* */
$date = date('Y-m-d', time());
$filename = 'Ud'.$id.$date.'.png'; //用时间戳生成一个图片名
$myfile = $_SERVER['DOCUMENT_ROOT'] . '/static/admin/uploads/headphoto/'; //定义图片所在位置
if (!is_dir($myfile)){
mkdir($myfile,0777,true); //检查陌路是否存在 不存在创建成777权限的目录
}
file_put_contents($myfile.$filename,base64_decode($photo)); //将接受的图片二进制流写入文件
分享结束,帮到您的给点个赞!!!