迷失的小屋
首页
注册

[WeiXinStable]2025/4/29图片上传下载

迷失的蒙娜丽莎
迷失的蒙娜丽莎
2025-04-29 09:42:45

wxml

<navigation-bar title="头像上传与下载" back="{{false}}" color="black" background="#FFF"></navigation-bar>
<view class="imgbox">
<image src="{{imgUrl}}" mode=""/>
<button bind:tap="changeImg" type="primary" size="mini">更改头像</button>
<button bind:tap="upload" type="primary" size="mini">上传头像</button>
<button bind:tap="download" type="primary" size="mini">下载头像</button>
</view>

wxss

/**index.wxss**/
.imgbox{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.imgbox image{
  width: 300rpx;
  height: 300rpx;
  border:1rpx solid gray;
}
.imgbox button {
  margin-top:50rpx;
}

js

// index.js
Page({
  data:{
    imgUrl:"",
    tempFilePath:null
  },
  upFilePath:"",
  changeImg(){
    wx.chooseMedia({
      count:1,
      mediaType:["image"],
      sourceType:["album","camera"],
      success:res=>{
        var temp=res.tempFiles[0].tempFilePath
        this.setData({
          imgUrl:temp,
          tempFilePath:temp
        })
      }
    })
  },
  upload(){
    if(!this.data.tempFilePath){
      wx.showToast({
        title:'请先选择图片在进行上传操作',
        icon:"none",
        duration:2000
      })
      return
    }
      wx.uploadFile({
       filePath: this.data.tempFilePath,
       name: 'image',
       url: 'http://172.16.90.12:3000/upload',
       success:res=>{
          this.upFilePath=JSON.parse(res.data).file
       }
     })
  },
  download(){
    if(!this.upFilePath){
      wx.showToast({
        title:'请先上传图片在进行上传操作',
        icon:"none",
        duration:2000
      })
      return
    }
    wx.downloadFile({
      url: this.upFilePath,
      success:res=>{
        wx.previewImage({
          urls: [res.tempFilePath],
        })
      }
    })
  }
})