微信小程序图片上传核心流程概述
在微信小程序开发中,将图片上传至服务器是常见功能需求。
首先需要在页面前端构建用于选择图片的交互区域,以此触发 wx.chooseImage 接口获取图片资源,随后利用 wx.setStorage 接口将获取到的图片本地路径进行持久化存储。

-wxml
发布项目
/**选择图片 */
choose: function () {
var that = this
wx.chooseImage({
count: 1,
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var tempFilePaths = res.tempFilePaths
that.setData({
tempFilePaths: res.tempFilePaths
})
console.log(res.tempFilePaths)
wx.setStorage({ key: "card", data: tempFilePaths[0] })
}
})
},
接着,调用 wx.uploadFile 接口,读取之前存储的图片路径,将其作为文件资源上传至配置的服务器地址。
formSubmit2: function (e) {
var that = this
var card = wx.getStorageSync('card')
wx.uploadFile({
url: app.globalData.create_funds,
filePath: card,
name: 'card',
formData: {
'user_id': app.globalData.user_id,
'person': e.detail.value.person,
'company': e.detail.value.company,
},
success: function (res) {
console.log(res)
}
})
}
}
},
以下方案支持单张或多张图片的上传处理逻辑。
该功能主要涉及两个核心步骤:
第一步是选取图片,即通过系统接口让用户从相册或相机中选择图像。
wx.chooseImage({
sizeType: [], // original 原图,compressed 压缩图,默认二者都有
sourceType: [], // album 从相册选图,camera 使用相机,默认二者都有
success: function (res) {
console.log(res);
var array = res.tempFilePaths, //图片的本地文件路径列表
}
})
第二步是执行上传操作,即将选中的图片数据发送至后端服务。
wx.uploadFile({
url: '', //开发者服务器的 url
filePath: '', // 要上传文件资源的路径 String类型!!!
name: 'uploadFile', // 文件对应的 key ,(后台接口规定的关于图片的请求参数)
header: {
'content-type': 'multipart/form-data'
}, // 设置请求的 header
formData: { }, // HTTP 请求中其他额外的参数
success: function (res) {
},
fail: function (res) {
}
})
以下是具体的代码实现示例。
// 点击上传图片
upShopLogo: function () {
var that = this;
wx.showActionSheet({
itemList: ['从相册中选择', '拍照'],
itemColor: "#f7982a",
success: function (res) {
if (!res.cancel) {
if (res.tapIndex == 0) {
that.chooseWxImageShop('album')
} else if (res.tapIndex == 1) {
that.chooseWxImageShop('camera')
}
}
}
})
},
chooseWxImageShop: function (type) {
var that = this;
wx.chooseImage({
sizeType: ['original', 'compressed'],
sourceType: [type],
success: function (res) {
/*上传单张
that.data.orderDetail.shopImage = res.tempFilePaths[0],
that.upload_file(API_URL + 'shop/shopIcon', res.tempFilePaths[0])
*/
/*上传多张(遍历数组,一次传一张)
for (var index in res.tempFilePaths) {
that.upload_file(API_URL + 'shop/shopImage', res.tempFilePaths[index])
}
*/
}
})
},
upload_file: function (url, filePath) {
var that = this;
wx.uploadFile({
url: url,
filePath: filePath,
name: 'uploadFile',
header: {
'content-type': 'multipart/form-data'
}, // 设置请求的 header
formData: { 'shopId': wx.getStorageSync('shopId') }, // HTTP 请求中其他额外的 form data
success: function (res) {
wx.showToast({
title: "图片修改成功",
icon: 'success',
duration: 700
})
},
fail: function (res) {
}
})
},
综上所述,以上内容由小编整理提供的微信小程序上传图片至服务器的实例代码,旨在为开发者提供参考与帮助。若在使用过程中遇到任何疑问,欢迎留言交流,小编将及时予以回复。同时,非常感谢各位读者对本站网站的支持!
以上所述是小编给大家介绍的微信小程序上传图片到服务器实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!