[小程序]向服务器上传图片和从服务器下载图片

本例的服务器基于flask,配置flask可以参见[Flask]上传多个文件到服务器icon-default.png?t=N7T8https://blog.csdn.net/weixin_37878740/article/details/128435136?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170581653516800185854860%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=170581653516800185854860&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_ecpm_v1~rank_v31_ecpm-5-128435136-null-null.nonecase&utm_term=flask&spm=1018.2226.3001.4450

一、上传图片

        在这里使用POST协议将图片上传到服务器,服务器代码为:

@app.route('/uploader', methods=['POST'])
def uploader():
    i=0
    for img in request.files.getlist('photo'):
        suffix = '.' + img.filename.split('.')[-1] # 获取文件后缀名
        img_path = './static/uploads/' + str(int(time.time())) +'_p'+str(i) + suffix # 拼接路径
        img.save(img_path) #保存图片
        print(img_path)
        i=i + 1 #序号戳记++
    return {'msg':'ok'}

        微信端代码为:

postImg(e){
    const that = this
    //选择图片
    wx.chooseImage({
      count:1,  //选择张数
      sizeType:['compressed'],   //是否压缩图
      sourceType:['album','camera'],  //数据源
      success(res){
        let tempFilePath = res.tempFilePaths; //图片的本地路径
        that.upload(that,tempFilePath); //上传图片
      }
    })
  },

        使用微信提供的wx.chooseImage选择图片,其中upload为单独封装的函数,实质上是一个Post函数,如下:

//上传函数
  upload(page,path){
    wx.showToast({
      icon:'loading',
      title: '正在上传',
    })
    wx.uploadFile({
      filePath: path[0],
      name: 'photo',
      url: '链接/uploader',
      header: {"Content-Type": "multipart/form-data"},
      //formData:{'session_token':wx.getStorageSync('session_token')},  //放置token
      success(res) {
        console.log(res.data);},
      fail(res){
        console.log(res)}
    })
  },

        需要注意的是,这个方法只会上传第一张图片,如果需要多张上传,需要在let tempFilePath = res.tempFilePaths;处对图片进行循环解析

二、获取图片

        其思路为:设置一个图片路径字符串变量,通过get指令让其等于服务器中的图片地址即可。

        flask端代码为:

@app.route('/getImg',methods=['GET'])
def getImg():
    idx = request.args.get("index",default=1,type=int)      #参数名,默认参数,参数类型
    ImgPath = 'static/src/{}.jpg'.format(idx)
    return "{}".format(ImgPath)

        微信端的代码为:

getImg(e){
    const that = this
     wx.request({
       url:'链接',
       method:'GET',
       data:{
          index:1,
       },
       success(res) {
         console.log(res.data);
         that.setData({imgUrl: '服务器绝对路径/'+res.data });
       },
       fail(res){
         console.log(res)
       }
     });  
   },

[小程序]向服务器上传图片和从服务器下载图片_第1张图片

你可能感兴趣的:(工程实践,小程序,服务器,运维)