需求分析
在微信小程序中需要使用手機(jī)拍攝照片以及視頻上傳到后臺進(jìn)行進(jìn)一步的操作,需要解決以下兩個(gè)問題:
- 微信小程序如何拍攝照片及視頻
- 如何將拍攝的照片及視頻上傳到后臺進(jìn)行存儲
解決方案
前端開發(fā):微信小程序原生
后端開發(fā):Flask
如何拍攝照片及視頻
微信小程序如何拍攝照片及視頻:使用wx.chooseMedia
API來實(shí)現(xiàn)
該API用于拍攝或從手機(jī)相冊中選擇圖片或視頻,文檔鏈接為:wx.chooseMedia(Object object) | 微信開放文檔
簡單示例:
function test()
{
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['camera'],
camera: 'back',
success(res) {
console.log(res)
},
fail(res){
console.log(res)
}
})
}
主要參數(shù)含義如下:
- count:最多可以選擇的文件個(gè)數(shù)
- mediaType:文件類型,可選值為:['image']/['video']/['image','video'],默認(rèn)值為['image','video'],意為即允許拍攝圖片也允許拍攝視頻
- sourceType:文件來源,可選值為['album']/[ 'camera']/['album', 'camera'],默認(rèn)值為['album', 'camera'],意為即允許從相冊選擇,也允許直接拍攝
- camera:僅在 sourceType 為 camera 時(shí)生效,使用前置或后置攝像頭,可選值為'back'/'front',默認(rèn)值為'back'
回調(diào)參數(shù)res內(nèi)容如下:
- tempFiles:本地臨時(shí)文件列表,其中的tempFilePath是本地臨時(shí)文件路徑,也是該示例中的核心參數(shù);
- type:文件類型
(更多參數(shù)以及回調(diào)參數(shù)請參考官方文檔)
由上可知,我們首選需要調(diào)用wx.chooseMedia
函數(shù),選擇拍攝照片或者視頻,然后在回調(diào)函數(shù)中拿到本地臨時(shí)文件路徑,這樣就獲取到了拍攝的照片或視頻,但我們拿到的并不是一個(gè)完整的.png/.mp4文件,而是一個(gè)臨時(shí)文件鏈接,例如:http://tmp/z7bXVKwgyWTKcbc89c663afd501de1d27ed321f8591c.jpg
這樣的文件鏈接可以在開發(fā)者工具中打開:
但該鏈接無法在外部進(jìn)行訪問,因此就涉及到如何將該鏈接所代表的文件上傳到后臺的問題;
這樣的文件在小程序中被稱為”本地臨時(shí)文件“,僅在當(dāng)前生命周期內(nèi)保證有效,重啟之后不一定可用;更多內(nèi)容請參考官方文檔:文件系統(tǒng) | 微信開放文檔
如何上傳后臺進(jìn)行存儲
如何將拍攝的照片及視頻上傳到后臺進(jìn)行存儲:
- 前端:使用
wx.uploadFile
API - 后端:使用
request.files['photo'].stream.read()
來讀取文件
前端代碼
有關(guān)wx.uploadFile
可以參考:UploadTask | 微信開放文檔
主要參數(shù)有:
- url:開發(fā)者服務(wù)器地址,即要訪問的接口
- filePath:要上傳的文件路徑(本地路徑),這里即是通過
wx.chooseMedia
回調(diào)中的tempFilePath - formData:HTTP 請求中其他額外的 form data,允許我們傳輸文件的時(shí)候攜帶一些其他的參數(shù),比如說文件名稱;
因此完整的前端代碼如下(上傳圖片):
//拍攝照片
photoCapture() {
let that = this
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['camera'],
camera: 'back',
success(res) {
that.setData({
photoLink: res.tempFiles[0].tempFilePath,
})
console.log(res.tempFiles[0].tempFilePath)
console.log('圖片拍攝成功')
wx.showLoading({
title: '正在上傳圖片',
mask: true
})
//圖片上傳
wx.uploadFile({
url: 'http://localhost:5000/uploadImage',
filePath: res.tempFiles[0].tempFilePath,
name: 'photo',
formData: {
fileName: 'photoTest.png'
},
success(res) {
wx.showToast({
title: '圖片上傳成功',
})
}
})
},
fail(res) {
console.log('圖片拍攝失敗')
}
})
}
首先拍攝照片,然后上傳文件
后端代碼
后端使用flask進(jìn)行開發(fā)
通過request.files
來接收文件
通過request.form
來接收wx.uploadFile
的formData
中攜帶的數(shù)據(jù)
通過write
方法將接收到的文件保存到本地
因此完整的后端代碼如下(上傳圖片):
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
# 圖片上傳
@app.route('/uploadImage', methods=["POST"])
def uploadImage():
video = request.files['photo'].stream.read()
name = request.form['fileName']
if not files_exists(name, 2):
file_path = os.getcwd() + '\\images\\' + name
with open(file_path, 'ab') as f:
f.write(video)
return 'image upload success'
else:
return 'image already exist'
# 判斷文件是否已經(jīng)存在
def files_exists(file_name, choice):
if choice == 1:
path = os.getcwd() + '\\videos\\'
video_path = os.path.join(path, file_name)
return os.path.isfile(video_path)
else:
path = os.getcwd() + '\\images\\'
image_path = os.path.join(path, file_name)
return os.path.isfile(image_path)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
運(yùn)行結(jié)果
首先啟動(dòng)后端服務(wù),然后小程序初始頁面如下:
點(diǎn)擊按鈕拍攝圖片,可以看到圖片成功預(yù)覽在小程序中:
在NetWork中可以看到接口的返回值:
圖片上傳成功;在后端也能看到圖片已經(jīng)保存下來了:
所有代碼
完整代碼可以從這里下載:
微信小程序上傳圖片視頻到后臺存儲demo資源-CSDN文庫
前后端代碼都有
前端代碼
index.wxml:
<button type="primary" bind:tap="photoCapture">點(diǎn)擊拍攝圖片</button>
<image src="{{photoLink}}"></image>
<button type="primary" bind:tap="videoCapture">點(diǎn)擊拍攝視頻</button>
<image src="{{videoLink}}"></image>
index.wxss:
page {
padding-top: 100rpx;
height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
}
image{
margin-top: 50rpx;
margin-bottom: 50rpx;
width: 600rpx;
height: 400rpx;
border: 1px solid black;
}
index.js:
Page({
data: {
photoLink: '',
videoLink: '',
},
//拍攝照片
photoCapture() {
let that = this
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['camera'],
camera: 'back',
success(res) {
that.setData({
photoLink: res.tempFiles[0].tempFilePath,
})
console.log(res.tempFiles[0].tempFilePath)
console.log('圖片拍攝成功')
wx.showLoading({
title: '正在上傳圖片',
mask: true
})
//圖片上傳
wx.uploadFile({
url:'http://localhost:5000/uploadImage',
filePath: res.tempFiles[0].tempFilePath,
name: 'photo',
formData: {
fileName:'photoTest.png'
},
success(res) {
wx.showToast({
title: res.data,
})
}
})
},
fail(res) {
console.log('圖片拍攝失敗')
}
})
},
//拍攝視頻
videoCapture() {
let that = this
wx.chooseMedia({
count: 1,
mediaType: ['video'],
sourceType: ['camera'],
maxDuration: 60,
camera: 'back',
success(res) {
that.setData({
videoLink: res.tempFiles[0].thumbTempFilePath
})
console.log('視頻拍攝成功')
console.log(res.tempFiles[0].tempFilePath)
wx.showLoading({
title: '正在上傳視頻',
mask: true
})
//視頻上傳
wx.uploadFile({
url:'http://localhost:5000/uploadVideo',
filePath: res.tempFiles[0].tempFilePath,
name: 'video',
formData: {
fileName:'videoTest.mp4'
},
success(res) {
wx.showToast({
title: res.data,
})
}
})
},
fail(res) {
console.log('圖片拍攝失敗')
}
})
}
})
后端代碼
from flask import Flask, request
import os
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
@app.route('/uploadVideo', methods=["POST"])
def uploadVideo():
video = request.files['video'].stream.read()
name = request.form['fileName']
if not files_exists(name, 1):
file_path = os.getcwd() + '\\videos\\' + name
with open(file_path, 'ab') as f:
f.write(video)
return 'upload success'
else:
return 'already exist'
@app.route('/uploadImage', methods=["POST"])
def uploadImage():
video = request.files['photo'].stream.read()
name = request.form['fileName']
if not files_exists(name, 2):
file_path = os.getcwd() + '\\images\\' + name
with open(file_path, 'ab') as f:
f.write(video)
return 'upload success'
else:
return 'already exist'
def files_exists(file_name, choice):
if choice == 1:
path = os.getcwd() + '\\videos\\'
video_path = os.path.join(path, file_name)
return os.path.isfile(video_path)
else:
path = os.getcwd() + '\\images\\'
image_path = os.path.join(path, file_name)
return os.path.isfile(image_path)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000)
此外文件上傳到后臺也可以采用base64編碼的方式進(jìn)行上傳
在我的這篇文章的【頭像昵稱填寫】部分有所提及:微信小程序用戶登錄及頭像昵稱設(shè)置教程(前后端)_微信小程序-原生開發(fā)用戶登錄-CSDN博客文章來源:http://www.zghlxwxcb.cn/news/detail-808864.html
歡迎大家討論交流~?文章來源地址http://www.zghlxwxcb.cn/news/detail-808864.html
到了這里,關(guān)于【教程】微信小程序如何拍攝圖片及視頻并上傳到后臺進(jìn)行存儲的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!