微信小程序上传图片其实很简单,闲话也不多说了,直接上代码,具体的步骤,会在下面加注释的,如果有疑问的可以在下面对我留言
- wx.chooseImage({}) 从本地相册选择图片或使用相机拍照。
- wx.uploadFile({}) 将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中
content-type
为multipart/form-data
html代码部分
<view bindtap="uploadImage"></view>
js代码部分
//chooseImage
uploadImage(){
wx.chooseImage({
count: 9, // 最多可以选择的图片张数,默认9
sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
success: (res) => {
const {
errMsg, tempFilePaths, tempFiles } = res;
tempFilePaths.forEach((filePath, index) => {
if (errMsg === 'chooseImage:ok') {
this.uploadFile(filePath);
}
});
},
});
}
//uploadFile
uploadFile(){
wx.uploadFile({
url: imageUpload,//这里是后台服务器的请求地址
filePath: filePath,//图片url
name: 'file',
header: {
'content-type': 'multipart/form-data' },//设置图片上传时的请求头
formData: {
},//如果上传图片api有其他的参数,可以在这里添加
success: (res) => {
//上传服务器成功之后可以对url处理,例如图片预览,长按删除等功能
},
fail: (error) => {
console.log(error);
},
});
}
//图片预览
previewImage(e) {
wx.previewImage({
current: e.currentTarget.dataset.path,
urls: this.data.imglist,//数组,需要预览的图片数组
success: function (res) {
},
fail: function () {
// fail
},
complete: function () {
// complete
},
});
},
//长按删除,选择需要上传的图片,不想上传的图片,给他去掉,需要添加事件 bind:longpress="longpress"
//longpress是一个长按的事件
longpress(e) {
const index = e.currentTarget.dataset.index;
const {
str } = this.data;
str.splice(index, 1);
this.setData({
str: str });
},