微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

微信小程序上传图片到服务器实例代码

上传图片到服务器:

1.先在前端写一个选择图片的区域来触发wx.chooseImage接口并用wx.setStorage接口把图片路径存起来。

这里写图片描述

rush:js;"> -wxml

2.使用wx.uploadFile将刚才上传图片上传到服务器上

rush:js;"> 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) } }) } } },

PS: 微信小程序上传一或多张图片

一.要点

1.选取图片

rush:js;"> wx.chooseImage({ sizeType: [],// original 原图,compressed 压缩图,认二者都有 sourceType: [],// album 从相册选图,camera 使用相机,认二者都有 success: function (res) { console.log(res); var array = res.tempFilePaths,//图片的本地文件路径列表 } })

2.上传图片

rush:js;"> wx.uploadFile({ url: '',//开发者服务器的 url filePath: '',// 要上传文件资源的路径 String类型!!! name: 'uploadFile',// 文件对应的 key,(后台接口规定的关于图片的请求参数) header: { 'content-type': 'multipart/form-data' },// 设置请求的 header formData: { },// HTTP 请求中其他额外的参数 success: function (res) { },fail: function (res) { } })

二.代码示例

rush:js;"> // 点击上传图片 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',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) { } }) },

总结

以上所述是小编给大家介绍的微信小程序上传图片到服务器实例代码。编程之家 jb51.cc 收集整理的教程希望能对你有所帮助,如果觉得编程之家不错,可分享给好友!感谢支持

原文地址:https://www.jb51.cc/weapp/35327.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。