微信小程序--uploadFile上传图片及踩坑


判断后台获取有没有用户头像
<view bindtap="uploadImage"  class="vieimg">
    <image wx:if="{{UserImg}}" src="{{UserImg}}"></image>
    <image wx:else src="/images/icon-boy.png"></image>
</view>
微信开发者工具有上传文件的方法

方法 wx.chooseImage 里边的参数有 count 为最多可已选择的图片总数,sizeType 指定原图还是压缩图片,默认是二者都有,sourceType 指定来源是相册还是相机,默认二者都有。代码如下:

wx.chooseImage({
    count: 1,
    sizeType: ['compressed'], 
    sourceType: ['album', 'camera'], 
    success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        wx.getFileSystemManager().readFile({
            filePath: tempFilePaths[0],
            encoding: 'base64',
            success: function(res) {
                var base64Img = 'data:image/png;base64,' + wx.arrayBufferToBase64(base)
                that.setData({
                    UserImg : tempFilePaths[0] //创建一个object URL,并不是你的本地路径
                })
            }
        })
    },
    fail: function (res) {}
})

wx.getFileSystemManager().readFile({}) 将获取到的图片文件转为base64

之前一直疑惑把图片存储到数据库中,怎么返回一个名称并且通过这个名称到文件中查找,后来发现C#中有接收文件的方法,可以到我上个随笔中看看 ➡️ C#接收前端上传图片

接着继续上传到后端,微信小程序给出了一个上传文件的方法wx.uploadFile({}}) 里边的参数和平常使用的有些出入

wx.uploadFile({ 
    url: url,//接口地址
    name: 'uploadfile_ant',//文件类型
    filePath: tempFilePaths[0],//为文件地址
    formData: {   //其他要传输给后端的数据,在这里不用传文件
        'id':UserImgid
    },
    success: function (res) {
        if(res.data==""){
            wx.showModal({
                title: '提示',
                content: "图片上传类型错误,当前支持jpg、png、bmp、jpeg、gif",
                showCancel: false
            });
        }
        //可以把后端传过来的已经成功的图片显示在页面上,注意url为你后端的文件存放地址
        that.setData({
            'UserImg': url+res.data.UserImg
        })
        wx.setStorageSync('UserImg', url+res.data.UserImg);
    },
    fail: function (res) {
        wx.showModal({
            title: '错误提示',
            content: "错误",
            showCancel: false,
            success: function (res) { }
        })
    }
})

踩坑:测试和本地调试都可以,发布后在手机上就不行,解决方法:

注意 wx.uploadFile 方法在发布前要在 微信小程序开发平台 页面配置服务器域名
在开发者工具里边
取掉勾选不校验

到这里基本上就结束了。😄​ ,有什么其他想法或问题的可以留言


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM