第一步:辅助函数;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function getSuffix(filename) { let pos = filename.lastIndexOf('.'); let suffix = ''; if (pos != -1) { suffix = filename.substring(pos); } return suffix; }
function getFileName(file, filename) { return ( file + Math.random() .toString(36) .substring(3, 20) + new Date().getTime() + getSuffix(filename) ); }
|
第二步:暴露出的图片上传函数;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| export function uploadImg(file) { return new Promise((resolve, reject) => { uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: function(res) { let Imgsrc = res.tempFilePaths[0]; let fileName = getFileName(file, Imgsrc); fileUpload("image", Imgsrc, fileName).then(res => { resolve(res) }).catch(err => { reject(err) }); } }) }) }
|
第三步:文件上传核心函数;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| function fileUpload(type, path, stroeAs) { uni.showLoading({ title: '文件上传中' }); return new Promise((resolve, reject) => { uni.request({ url: 'xxxxxxxxxxxxxxxxxxxxx', complete: res => { var data = res.data; uni.uploadFile({ url: data.host, filePath: path, fileType: type, name: 'file', formData: { key: stroeAs, policy: data.policy, OSSAccessKeyId: data.accessid, success_action_status: '200', signature: data.signature }, success: res => { uni.hideLoading(); uni.showToast({ title: '上传成功', icon: 'success', duration: 2000 }); resolve(data.host + stroeAs) }, fail: err => { reject(err) uni.hideLoading(); uni.showModal({ content: err.errMsg, showCancel: false }); } }); } }) }); }
|
第四步:暴露出的视频上传函数;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| export function uploadVid(file) { return new Promise((resolve, reject) => { uni.chooseVideo({ count: 1, sourceType: ['camera', 'album'], success: function(res) { let videoSrc = res.tempFilePath; if (res.size > 1024 * 1024 * 15) { uni.showToast({ title: '文件大小超过系统上传限制:15M', icon: 'none', duration: 1000 }); return; } let fileName = getFileName("video", file, videoSrc); fileUpload("video",Imgsrc, fileName).then(res => { resolve(res) }).catch(err => { reject(err) }); }, fail: (err) => { reject(err) uni.showToast({ title: '取消选择视频', icon: 'none', duration: 2000 }); } }) }) }
|
文件下载地址:CSDN0积分下载 或者 uniapp插件市场下载
相关说明
| 参数 |
类型 |
说明 |
| file |
String |
要存放的文件夹名;例如 …/imageList/ |
| filename |
Blob |
被选中的图片或者视频文件名 |
| type |
String |
image 或者 video |
| path |
Blob |
同filename被选中的本地图片或视频文件 |
| stroeAs |
String |
自定义文件名;例如 …/imageList/xxxx.png |