欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序学习笔记之文件上传、下载操作图文详解

程序员文章站 2023-12-03 21:01:40
本文实例讲述了微信小程序学习笔记之文件上传、下载操作。分享给大家供大家参考,具体如下: 前面介绍了微信小程序登录api与获取用户信息操作。这里再来介绍一下文件的上传与下载...

本文实例讲述了微信小程序学习笔记之文件上传、下载操作。分享给大家供大家参考,具体如下:

前面介绍了微信小程序登录api与获取用户信息操作。这里再来介绍一下文件的上传与下载操作。

【文件上传】wx.uploadfile

(以上传图片为例)

后台上传接口upload.php:(tp5)

<?php
namespace app\home\controller;
use think\controller;
class upload extends first
{
  //上传图片api
  public function upimg() {
  	$arr = array('state'=>0,'msg'=>'上传失败','filepath'=>'');
    $file = request()->file('file');
    if($file){
      $info = $file->move('upload/weixin/');
      if ($info) {
        $arr['state'] = 1;
        $arr['msg'] = '上传成功';
        $arr['filepath'] = $info->getsavename();
      }
    }
    return json($arr);
  }
}

前台页面upload.wxml:

<image src='{{imgpath}}' style='width:600rpx; height:600rpx' />
<view>
 <button bindtap="upimg">点击选择上传图</button>
</view>

前台upload.js:

page({
 data: {
  imgpath: ''
 },
 upimg: function (e) {
  var that = this
  wx.chooseimage({
   count: 1, // 默认最多一次上传9张图片
   sizetype: ['original', 'compressed'], // 允许原图和压缩图
   sourcetype: ['album', 'camera'], // 允许相册和相机
   success(res) {
    const tempfilepaths = res.tempfilepaths
    wx.showtoast({
     title: '正在上传...',
     icon: 'loading',
     mask: true,
     duration: 500
    })
    wx.uploadfile({
     url: 'https://www.msllws.top/upload/upimg', //服务器上传接口
     filepath: tempfilepaths[0], //文件资源路径
     name: 'file',
     header: {
      'content-type': 'application/json'
     },
     success(res) {
      console.log(res)
      if (res.statuscode == 200){
       that.setdata({
        imgpath: tempfilepaths
       }) 
      }
     }
    })
   }
  })
 }
})

演示效果:

微信小程序学习笔记之文件上传、下载操作图文详解

(其实是有正在上传...效果的,手机录屏没给录上。。)

微信小程序学习笔记之文件上传、下载操作图文详解

微信小程序学习笔记之文件上传、下载操作图文详解 
查看服务器里面多了一张图片:

微信小程序学习笔记之文件上传、下载操作图文详解

嗯哼~

微信小程序学习笔记之文件上传、下载操作图文详解

 【文件下载】wx.downloadfile

(以下载一张图片为例)

在服务器目录下放一张图片1.jpg:

微信小程序学习笔记之文件上传、下载操作图文详解

微信小程序学习笔记之文件上传、下载操作图文详解

download.wxml:

<image src='{{imgpath}}' style='width:600rpx; height:600rpx' />
<view>
 <button bindtap="download">点击下载</button>
</view>

download.js:

page({
 data: {
  imgpath: ''
 },
 download: function (e) {
  var that = this
  wx.showtoast({
   title: '正在下载...',
   icon: 'loading',
   mask: true,
   duration: 500
  })
  wx.downloadfile({
   url: 'https://www.msllws.top/upload/1.jpg', //下载地址 
   type: 'image', //下载的资源类型(imnage/audio/video)
   success: function (res) {
    console.log(res)
    if (res.statuscode == 200) {
     var filepath = res.tempfilepath
     that.setdata({
      imgpath: filepath
     })
    }
   }
  })
 }
})

演示效果:

微信小程序学习笔记之文件上传、下载操作图文详解

微信小程序学习笔记之文件上传、下载操作图文详解 微信小程序学习笔记之文件上传、下载操作图文详解

希望本文所述对大家微信小程序开发有所帮助。