微信小程序學習筆記之文件上傳、下載操作圖文詳解
本文實例講述了微信小程序學習筆記之文件上傳、下載操作。分享給大家供大家參考,具體如下:
前面介紹了微信小程序登錄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
})
}
}
})
}
})
演示效果:


希望本文所述對大家微信小程序開發(fā)有所幫助。
相關文章
Bootstrap警告(Alerts)的實現(xiàn)方法
這篇文章主要為大家詳細介紹了Bootstrap警告(Alerts)的實現(xiàn)方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
Bootstrap模塊dropdown實現(xiàn)下拉框響應
這篇文章主要為大家詳細介紹了Bootstrap下拉框模塊dropdown實現(xiàn)下拉框響應,感興趣的朋友可以參考一下2016-05-05
uniapp中uni.navigateBack返回后刷新頁面數(shù)據(jù)的實現(xiàn)
本文主要介紹了uniapp中uni.navigateBack返回后刷新頁面數(shù)據(jù)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11
javascript中Date()函數(shù)在各瀏覽器中的顯示效果
本文給大家分享的是javascript中Date()函數(shù)在各瀏覽器中的顯示效果,由于各大瀏覽器的兼容性問題,本文做了這個測試,希望有需要的小伙伴可以少走些彎路2015-06-06

