微信小程序如何实现文件上传、下载操作

发布时间:2021-07-19 09:37:31 作者:小新
来源:亿速云 阅读:495

这篇文章将为大家详细讲解有关微信小程序如何实现文件上传、下载操作,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

具体如下:

前面介绍了微信小程序登录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
     })
    }
   }
  })
 }
})

演示效果:

微信小程序如何实现文件上传、下载操作

微信小程序如何实现文件上传、下载操作 微信小程序如何实现文件上传、下载操作

关于“微信小程序如何实现文件上传、下载操作”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. 微信小程序如何实现滑动
  2. 微信小程序中怎么实现事件交互操作

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序

上一篇:css有哪些结构化伪类选择器

下一篇:python中PaddleOCR库的用法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》