1、微信小程序上传图片
<view bindtap="uploadImg">上传图片</view>
/*上传文件需要先通过 wx.chooseImage 等接口获取到一个本地资源的临时文件路径后,再通过上传文件接口将本地资源上传到指定服务器。*/
uploadImg: function () {
wx.chooseImage({
count: 1, // 默认9
sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ["album", "camera"], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
var tempFilePaths = res.tempFilePaths; // ["http://tmp/xxxxxx.xxx.png"]
// 截取 “/” 前面的内容,后面的内容是上传的文件名
var Key = tempFilePaths[0].substr(tempFilePaths[0].lastIndexOf('/') + 1); // 这里指定上传的文件名
console.log(tempFilePaths[0]); // 在页面中显示出来的图片路径
this.setData({
pictureImg: tempFilePaths[0]
})
this.getToken(Key, tempFilePaths[0]); //获取上传图片前的token等信息
}
})
},
//获取上传图片前的token等信息
getToken(Key, imgurl) {
// 引入config文件中封装的allrequest小程序请求接口方法
config.allrequest('uploadToken', {
account: app.globalData.mobile,
access_code: app.globalData.access_code,
}, (res) => {
this.uploadUrl(res.data.data, Key, imgurl); //将本地得到的文件名和文件路径传入
})
},
//上传文件-上传图片路径
uploadUrl(tokenInfo, Key, imgurl) {
wx.uploadFile({
url: tokenInfo.host, //开发者服务器 url
filePath: imgurl, //要上传文件资源的路径
name: "file", //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 前端名字file是 上传到服务器的临时目录
formData: {
policy: tokenInfo.policy,
OSSAccessKeyId: tokenInfo.accessid,
success_action_status: '200',
callback: tokenInfo.callback,
signature: tokenInfo.signature,
key: tokenInfo.dir + Key // dir: attachment/20181012/
},
header: {
'content-type': 'multipart/form-data'
},
success: (res) => {
console.log(tokenInfo.host + '/' + Key)
// 服务器域名+ 域名里上传的路径 + 图片名 上传
config.allrequest('uploadtx', {
account: app.globalData.mobile,
access_code: app.globalData.access_code,
headpic: tokenInfo.host + '/' + Key
}, (res) => {
console.log(res)
})
},
fail: function (data) {
console.log(data);
}
})
},
2、公众号h5页面上传图片
方法一,通过jssdk上传
<div @click="uploadImg">
<img :src="pictureImg" />
</div>
uploadImg() {
// 通过接口得到微信验证的相关信息
// 引入api文件中封装的vue中axios请求接口方法
api.allAxios(this, 'getWeiXinScanParams', {
access_code: JSON.parse(localStorage.getItem("info")).access_code,
shopcode: this.shopcode,
requestRefererURL: location.href.split('#')[0],
type: 2
}, (res, images_url) => {
this.wxConfig(res.data.data);// 通过微信验证config
})
},
wxConfig(tokenInfo){
var that = this;
wx.config({
debug: false,
appId: tokenInfo.appid,
timestamp: tokenInfo.timestamp,
nonceStr: tokenInfo.nonceStr,
signature: tokenInfo.signature,
jsApiList: ["chooseImage", "uploadImage", "downloadImage", "getLocalImgData"]
});
wx.ready(function () {
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
wx.chooseImage({
count: 1, //一次性可以选择多少张图片,默认9
sizeType: ['compressed'], //图片的类型:原图,压缩图
sourceType: ['album', 'camera'], //图片来源:相册,拍照
success: function (res) {
var localIdVal = res.localIds[0]; //本地第一张图片ID
that.imgsrc = res.localIds[0]; // 在页面中显示出来的图片路径
wx.getLocalImgData({
localId: localIdVal, // 图片的localID
success: function (res) {
var localData = res.localData; // localData是图片的base64数据,可以用img标签显示
if (navigator.userAgent.indexOf('Android') > -1) {
//处理安卓
localData.replace('\n', '')
localData = 'data:image/jpg;base64,' + localData;
} else {
localData = localData.replace('jgp', 'jpeg');
}
that.uploadUrl(localData);//上传文件-上传图片路径
},
cancel: function (res) {
}
});
}
});
});
wx.error(function (res) {
// console.log(res);
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});
},
//上传文件-上传图片路径
uploadUrl(localData){
var that = this;
api.allAxios(that, 'postObjectPolicy', {}, (res) => {
var accessid = res.data.data.accessid;
var host = res.data.data.host;
var dir = res.data.data.dir; // attachment/20181012/
// 图像数据 (e.g. data:image/png;base64,iVBOR...yssDuN70DiAAAAABJRU5ErkJggg==)
var dataUrl = localData;
var base64 = dataUrl.split(',')[1];
var fileType = dataUrl.split(';')[0].split(':')[1];
// base64转blob
var blob = that.toBlob(base64, fileType);
// blob转arrayBuffer
var reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.onload = function (event) {
// 配置
var client = new OSS.Wrapper({
region: 'xxxx', //oss区域
accessKeyId: accessid, //key
accessKeySecret: 'xxxxxxx',
bucket: 'xxxxxxx' //阿里云oss的名称
});
// 文件名
var date = new Date();
// var time = ''+date.getFullYear()+date.getMonth()+1+date.getDate();
// var storeAs = 'Uploads/file/'+time+'/'+date.getTime()+'.'+blob.type.split('/')[1];
var storeAs = dir + date.getTime() + '.' + blob.type.split('/')[1];
// arrayBuffer转Buffer
var buffer = new OSS.Buffer(event.target.result);
// 直传 绕开微信上传
client.put(storeAs, buffer).then(function (result) {
// 服务器域名+ 域名里上传的路径 + 图片名 上传
that.pictureImg = host + '/' +result.name; // 上传到服务器带路径的图片路径
}).catch(function (err) {
// console.log(err);
});
}
})
}
// base64转blob
toBlob(urlData, fileType) {
var bytes = window.atob(urlData),
n = bytes.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bytes.charCodeAt(n);
}
return new Blob([u8arr], {
type: fileType
});
},
方法二,通过vant组件上传
<van-uploader :after-read="uploadImg">
<img :src="pictureImg" />
</van-uploader>
uploadImg(file) {
if (file.file.size > 500000) {
this.$toast({
message: '文件大小超过500k,请重新上传',
duration: 1000
})
return;
}
var localData = file.content; //base64形式的图片
this.uploadUrl(localData);//上传文件-上传图片路径
},