一、基本流程
图片、视频、音频的上传都是先通过uni的xx方法获取到临时路径,然后拿这个临时路径通过uni.uploadFile上传到公司的文件服务器中,返回文件路径
二、图片上传
图片使用uni.chooseMedia
js
uni.chooseMedia({
count: maxCount,
mediaType: ["image"],
sizeType: ["compressed"],
camera: "back",
success: (res) => {
const tempFiles = res.tempFiles;
const accept = ["jpg", "jpeg", "png", "JPG", "JPEG", "PNG"];
let fail = false;
tempFiles.forEach((item, index) => {
console.log("压缩之后的图片大小", item.size)
const extension = item.tempFilePath
.split(".")[1];
if (accept.indexOf(extension) === -1 || Number(item.size) >
Number(
5242880) ||
fileMap.imageUrls.length >= fileMap.maxSize
) {
fail = true;
} else {
this.uploadFile(item, fileMap);
}
});
if (fail) {
uni.showToast({
title: `仅支持照片文件,最大支持5M,最多传${fileMap.maxSize}张`,
icon: "none",
duration: 3000,
});
}
},
});
uni.loadFile上传至文件服务器
js
uploadFile(file, fileMap) {
this.showLoading = true;
// 以文件流的方式上传文件
uni.uploadFile({
url: config.baseUrl + '/common/uploadFile',
filePath: file.tempFilePath || '',
name: 'file',
formData: {},
headers: { 'Content-Type': 'multipart/form-data' },
success: (uploadFileRes) => {
this.showLoading = false;
console.log('uploadFileRes>>',uploadFileRes);
if (uploadFileRes && uploadFileRes.errMsg == 'uploadFile:ok') {
let picItem = uploadFileRes && uploadFileRes.data ? JSON.parse(uploadFileRes.data) || {} : {}
let url = picItem.data || ''
const result = { data: {url} }
this.addImageInfoEvt(fileMap, result) // 更新图片列表
}
},
fail: (err) => {
this.showLoading = false;
console.log('图片上传接口调用失败', err)
}
})
}
三、视频上传
视频使用uni.chooseVideo
js
chooseFile() {
uni.chooseVideo({
count: 1,
sourceType: ["camera", "album"],
maxDuration: 30,
mediaType: ["video"],
success: (res) => {
if (res.size / 1024 / 1024 > 50) {
return uni.showToast({
icon: "none",
title: "拍摄视频过大,请重新拍摄!",
});
}
this.uploadFile(res);
},
});
}
uni.loadFile上传至文件服务器
js
uploadFile(file) {
uni.showLoading({ title: "努力加载中", mask: true });
// 以文件流的方式上传文件
uni.uploadFile({
url: config.baseUrl + "/common/uploadFile",
filePath: file.tempFilePath || "",
name: "file",
formData: {},
headers: { "Content-Type": "multipart/form-data" },
success: async (uploadFileRes) => {
uni.hideLoading()
console.log("uploadFileRes>>", uploadFileRes);
if (uploadFileRes && uploadFileRes.errMsg == "uploadFile:ok") {
const item =
uploadFileRes && uploadFileRes.data
? JSON.parse(uploadFileRes.data) || {}
: {};
const params = {
applyId: this.applyId,
type: 1,
VEDIO_SP: item.data,
};
const { flag } = await this.$api.investigate.addImageInfoCredit(
params
);
if (flag) this.getImageInfoCredit();
}
},
fail: (err) => {
uni.hideLoading()
console.log("图片上传接口调用失败", err);
},
});
}
四、音频上传
音频上传,微信小程序不支持,可以使用uni.chooseMessageFile,从聊天记录中选中音频上传
js
chooseFile() {
uni.chooseMessageFile({
count: 1,
extension: [".mp3"],
success: (res) => {
console.log("从聊天记录中获取文件", res);
const { errMsg, tempFiles } = res;
if (errMsg == "chooseMessageFile:ok" && tempFiles.length) {
const { name, size, path } = tempFiles[0];
console.log("临时文件", { size, path });
if (name.slice(-4) != ".mp3") {
return uni.showToast({
icon: "none",
title: "请上传mp3文件!",
duration: 2000,
});
}
if (size / 1024 / 1024 > 50) {
return uni.showToast({
icon: "none",
title: "音频文件过大,请重新选择!",
});
}
this.uploadFile(path);
}
},
});
},
uni.loadFile上传至文件服务器
js
uploadFile(path) {
uni.showLoading({ title: "努力加载中", mask: true });
// 以文件流的方式上传文件
uni.uploadFile({
url: config.baseUrl + "/common/uploadFile",
filePath: path || "",
name: "file",
formData: {},
headers: { "Content-Type": "multipart/form-data" },
success: async (uploadFileRes) => {
uni.hideLoading();
console.log("uploadFileRes>>", uploadFileRes);
if (uploadFileRes && uploadFileRes.errMsg == "uploadFile:ok") {
const item =
uploadFileRes && uploadFileRes.data
? JSON.parse(uploadFileRes.data) || {}
: {};
const params = {
applyId: this.applyId,
type: 1,
VEDIO_LY: item.data,
};
const { flag } = await this.$api.investigate.addImageInfoCredit(
params
);
if (flag) this.getImageInfoCredit();
}
},
fail: (err) => {
uni.hideLoading();
console.log("图片上传接口调用失败", err);
},
});
}
4.1 音频播放
js
data() {
return {
audioUrls: [], // 音频列表
innerAudioContext: null,
currentIndex: "",
};
},
onLoad(query) {
this.getImageInfoCredit(); // 获取音频列表
this.initInnerAudioContext();
},
onHide() {
this.innerAudioContext && this.innerAudioContext.stop();
},
onUnload() {
this.innerAudioContext && this.innerAudioContext.stop();
},
methods: {
async getImageInfoCredit() {
const params = { applyId: this.applyId, type: 1 };
const { flag, data } = await this.$api.investigate.getImageInfoCredit(
params
);
if (flag) {
const list =
data.VEDIO_LY.map((item) => ({ audio: item, icon: "play-circle" })) ||
[];
this.audioUrls = list;
}
},
// 音频播放器初始化
initInnerAudioContext() {
this.innerAudioContext = uni.createInnerAudioContext();
this.innerAudioContext.autoplay = true;
this.innerAudioContext.obeyMuteSwitch = false;
this.innerAudioContext.sessionCategory = "playback";
this.innerAudioContext.onPlay(() => {
this.audioUrls = this.audioUrls.map((item, i) => ({
...item,
icon: this.currentIndex == i ? "pause-circle" : "play-circle",
}));
uni.showToast({ icon: "none", title: "开始播放", duration: 2000 });
});
this.innerAudioContext.onPause(() => {
this.audioUrls = this.audioUrls.map((item) => ({
...item,
icon: "play-circle",
}));
uni.showToast({ icon: "none", title: "暂停播放", duration: 2000 });
});
this.innerAudioContext.onEnded(() => {
this.audioUrls = this.audioUrls.map((item) => ({
...item,
icon: "play-circle",
}));
uni.showToast({ icon: "none", title: "播放完成", duration: 2000 });
});
this.innerAudioContext.onError((res) => {
uni.showToast({ icon: "none", title: "播放错误", duration: 2000 });
console.log("错误", res.errMsg);
console.log("错误", res.errCode);
});
},
handlePlay(item, index) {
this.innerAudioContext.src = item.audio;
if (item.icon == "play-circle") {
// 暂停时,继续播放
this.innerAudioContext.play();
this.currentIndex = index;
} else {
// 正在播放时,暂停播放
this.innerAudioContext.pause();
}
},
}