小程序上传图片到七牛
小程序上传图片非常简单,利用好2个API:
/**
* 上传图片
*/
chooseImageUpload() {
var that = this;
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: function (res) {
that.tempFilePaths = res.tempFilePaths;
that.uploadQiniu();
}
})
},
注意点:
- header头要写
- token 一定要去获取七牛的token
- filePath是单个图片就写下标0,如果多图片就用for循环吧,不过上个函数wx.chooseImage.count要配置1以上
- url写https://upload-z2.qiniup.com
/**
* 上传七牛返回key
*/
uploadQiniu() {
let token = this.uploadtoken.token;
let tempFilePaths = this.tempFilePaths;
var that = this;
wx.uploadFile({
url: 'https://upload-z2.qiniup.com',
name: 'file',
filePath: tempFilePaths[0],
header: {
"Content-Type": "multipart/form-data"
},
formData: {
token: token,
},
success: function (res) {
let data = JSON.parse(res.data)
// to do ...
},
fail: function (res) {
console.log(res)
}
})
},
看到返回key就是成功啦!!