上传图片方法到免费服务器

1. 使用的小白接口:App.CDN.UploadImg

链接:http://api.okayapi.com/?s=App.CDN.UploadImg

2. 小程序样例代码

wxml(添加图片就可以上传):

<view class="weui-uploader">

  <view class="weui-uploader__hd">
    <view class="weui-uploader__title">图片上传</view>
  </view>

  <view class="weui-uploader__bd">
    <block wx:for="{{imagesList}}" wx:key="*this" >
      <view class="weui-uploader__file">
        <image class="weui-uploader__img" src="{{item}}"></image>
      </view>
    </block>

    <view class="weui-uploader__input-box">
      <input class="weui-uploader__input js_file" type="file"
             accept="image/jpg,image/jpeg,image/png,image/gif"
             multiple="" bindtap='uploader' name="images"></input>
    </view>
  </view>

</view>

在这里插入图片描述

处理图片与请求服务(使用小程序的API:uploadFile)

请求成功返回七牛云链接

wx.chooseImage({

      count: 6, //最多可以选择的图片总数

      sizeType: ['original','compressed'], // 可以指定是原图还是压缩图,默认二者都有

      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有

      success: function(res) {

        wx.showToast({

          title: '正在上传...',

          icon: 'loading',

          mask: true,

          duration: 500

        })

        for(let i=0;i<res.tempFiles.length;i++){

          if(res.tempFiles[i].size>maxSize){

            flag=false;

            wx.showModal({

              content: '图片太大,不允许上传',

              showCancel: false,

              success: function (res) {

                if (res.confirm) {

                  console.log('用户点击确定')

                }

              }

            });

          }

        }

        const tempFilePaths = res.tempFilePaths[0]

        if (res.tempFiles.length>maxLength){
	          wx.showModal({

		            content: '最多能上传'+maxLength+'张图片',

		            showCancel:false,

		            success:function(res){
		
		              if(res.confirm){
		                console.log('确定');
		              }
		            }

          })

        }

        if (flag == true && res.tempFiles.length <= maxLength){

          that.setData({

            imagesList: res.tempFilePaths

          })

        }


				//请求接口

        wx.uploadFile({

          url: getApp().globalData.okayapiHost,

          filePath: tempFilePaths,

          name: 'file',

          header: {

            "Content-Type": "application/x-www-form-urlencoded"

          },

          formData: {
            file_name : 'Camaro.png',
            app_key : 'your appkey',
						s:"App.CDN.UploadImg"

          },

        })

        console.log(res);

      },
    })

已经上传完成

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值