在本文 微信小程序-從相冊(cè)獲取圖片 使用相機(jī)拍照 本地圖片上傳之前需要看看
微信小程序-獲取用戶session_key,openid,unionid - 后端為nodejs
代碼封裝是在上文添加的。
本文知識(shí)點(diǎn):
1、微信小程序選擇圖片wx.chooseImage()接口的使用
2、微信小程序選擇視頻wx.chooseVideo()接口的使用
3、微信小程序上傳文件接口wx.uploadFile()的使用
4、nodejs上傳文件multer模塊的使用
效果
image
注意:
1、在微信開(kāi)發(fā)工具里選擇視頻接口wx.chooseVideo()返回的數(shù)據(jù)有視頻縮略圖字段(thumbTempFilePath),在真機(jī)上沒(méi)有;
2、上傳視頻時(shí),compressed壓縮字段無(wú)效,不知是所有手機(jī)無(wú)效還是部分,本文測(cè)試時(shí),使用的是華為mate9,這也是小程序的深坑之一;
3、上傳視頻時(shí),使用錄制方式,華為mate9視頻大小過(guò)大,錄制的6秒鐘視頻就有20多M,網(wǎng)上說(shuō)好像mate9的視頻編碼格式是h265,普通手機(jī)為h264,也許是無(wú)法壓縮問(wèn)題引起的;
image
所以嘗試了另外一種方式錄制,使用camera組件,這種方式需要自己自定義錄制界面:點(diǎn)擊這里。
小程序代碼
在utils下的wechat.js文件里添加代碼,如有則忽略
/**
* 從本地相冊(cè)選擇圖片或使用相機(jī)拍照。
* @param {number} count 最多可選圖片的數(shù)量
* @param {array} sizeType original 原圖,compressed 壓縮圖
* @param {array} sourceType album 從相冊(cè)選圖,camera 使用相機(jī)
*/
static chooseImage(count = 1, sizeType = ['compressed'], sourceType = ['album', 'camera']) {
return new Promise((resolve, reject) => wx.chooseImage({ count, sizeType, sourceType, success: resolve, fail: reject }));
}
/**
* 拍攝視頻或從手機(jī)相冊(cè)中選視頻,返回視頻的臨時(shí)文件路徑。
* @param {boolean} compressed 是否壓縮
* @param {array} sourceType album 從相冊(cè)選圖,camera 使用相機(jī)
* @param {number} maxDuration 拍攝視頻最長(zhǎng)拍攝時(shí)間,單位秒。最長(zhǎng)支持 60 秒
*/
static chooseVideo(compressed = true, sourceType = ['album', 'camera'], maxDuration = 60) {
return new Promise((resolve, reject) => wx.chooseVideo({ sourceType, compressed, maxDuration, success: resolve, fail: reject }));
}
/**
* 將本地資源上傳到開(kāi)發(fā)者服務(wù)器,客戶端發(fā)起一個(gè) HTTPS POST 請(qǐng)求
* @param {string} url 開(kāi)發(fā)者服務(wù)器 url
* @param {string} filePath 要上傳文件資源的路徑
* @param {string} name
* @param {object} formData HTTP 請(qǐng)求中其他額外的 form data
*/
static uploadFile(url, filePath, name, formData = { openid: "test" }) {
return new Promise((resolve, reject) => {
let opts = { url, filePath, name, formData, header: { 'Content-Type': "multipart/form-data" }, success: resolve, fail: reject };
wx.uploadFile(opts);
});
}
js
let app = getApp();
let wechat = require("../../utils/wechat");
Page({
data: {
tempImagePath: "", // 拍照的臨時(shí)圖片地址
tempThumbPath: "", // 錄制視頻的臨時(shí)縮略圖地址
tempVideoPath: "", // 錄制視頻的臨時(shí)視頻地址
type: "chooseImage",
},
onLoad() {
},
camera(e) {
let { type } = e.target.dataset;
this.setData({
type
})
console.log("開(kāi)始上傳準(zhǔn)備", type == "chooseImage" ? "圖片" : "視頻");
// 拍照
if (type == "chooseImage") {
console.log("選擇圖片");
wechat.chooseImage()
.then(d => {
let { path, size } = d.tempFiles[0];
this.setData({
tempImagePath: path,
});
return wechat.uploadFile("https://xx.xxxxxx.cn/api/upload", path, "uploadImg")
})
.then(d => {
console.log(d);
})
.catch(e => {
console.log(e);
})
}
// 錄視頻
else if (type == "chooseVideo") {
wechat.chooseVideo()
.then(d => {
console.log(d);
let { tempFilePath, thumbTempFilePath, size } = d;
this.setData({
// tempThumbPath: thumbTempFilePath,
tempVideoPath: tempFilePath,
});
return wechat.uploadFile("https://xx.xxxxxx.cn/api/upload", tempFilePath, "tempVideoPath");
})
.then(d => {
console.log(d);
})
.catch(e => {
console.log(e);
})
}
}
})
html
<view class="view">
<view class="window">
<image class="cover-9" src="{{tempImagePath}}" bindtap="img" wx:if="{{type=='chooseImage'}}"></image>
<video class="cover-9" src="{{tempVideoPath}}" poster="{{tempThumbPath}}" wx:if="{{type=='chooseVideo'}}"></video>
<view class="window-2">
<button bindtap="camera" type="primary" data-type="chooseImage">圖片</button>
<button bindtap="camera" type="primary" data-type="chooseVideo">視頻</button>
</view>
</view>
</view>
css
page{
height: 100%;
}
.view{
width: 100%;
height: 100%;
}
.window{
width: 100%;
height: 100%;
}
.window-2{
display: flex;
flex-direction: row;
}
.cover-9{
width: 728rpx;
height: 80%;
margin: 0 10rpx;
border:2rpx solid;
border-radius:5px;
}
button{
margin: 0 10rpx;
width: 100%;
}
nodejs代碼
const multer = require('multer');
let path = require("path");
//上傳文件配置
const storage = multer.diskStorage({
//文件存儲(chǔ)位置
destination: (req, file, cb) => {
cb(null, path.resolve(__dirname, '../uploads/tmp/'));
},
//文件名
filename: (req, file, cb) => {
cb(null, `${Date.now()}_${Math.ceil(Math.random() * 1000)}_multer.${file.originalname.split('.').pop()}`);
}
});
const uploadCfg = {
storage: storage,
limits: {
//上傳文件的大小限制,單位bytes
fileSize: 1024 * 1024 * 20
}
};
router.post("/api/upload", async (req, res) => {
let upload = multer(uploadCfg).any();
upload(req, res, async (err) => {
if (err) {
res.json({ path: `//uploads/tmp/${uploadFile.filename}` });
console.log(err);
return;
};
console.log(req.files);
let uploadFile = req.files[0];
res.json({ path: `//uploads/tmp/${uploadFile.filename}` });
});
})
后端打印
image
上傳的文件
image