使用场景:
- uniapp-vue2语法
- uview
- 阿里云对象存储oss
使用步骤:
- 首先将uView引入我们创建的项目
- 然后测试是否引入成功
- 打开uView的官网介绍 | uView 2.0 - 全面兼容nvue的uni-app生态框架 - uni-app UI框架,找到上传然后将
<template> <u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10" ></u-upload> </template> <script> export default { data() { return { fileList1: [], } }, methods:{ // 删除图片 deletePic(event) { this[`fileList${event.name}`].splice(event.index, 1) }, // 新增图片 async afterRead(event) { // 当设置 multiple 为 true 时, file 为数组格式,否则为对象格式 let lists = [].concat(event.file) let fileListLen = this[`fileList${event.name}`].length lists.map((item) => { this[`fileList${event.name}`].push({ ...item, status: 'uploading', message: '上传中' }) }) for (let i = 0; i < lists.length; i++) { const result = await this.uploadFilePromise(lists[i].url) let item = this[`fileList${event.name}`][fileListLen] this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, { status: 'success', message: '', url: result })) fileListLen++ } }, uploadFilePromise(url) { return new Promise((resolve, reject) => { let a = uni.uploadFile({ url: 'http://192.168.2.21:7001/upload', // 仅为示例,非真实的接口地址 filePath: url, name: 'file', formData: { user: 'test' }, success: (res) => { setTimeout(() => { resolve(res.data.data) }, 1000) } }); }) }, } } </script>
复制到项目中,
-
根据uniapp官网uni.uploadFile(OBJECT) | uni-app官网uni.uploadFile为uniapp的api而formData该参数可以请求额外的form data
-
那么我们应该传哪些额外的参数呢?
-
可以查看阿里云对象存储的相关文档调用PostObject表单上传Object_对象存储-阿里云帮助中心看看哪些是必传的,哪些是非必传的
-
然后将参数传过去就可以了
let a = uni.uploadFile({ url: " ", // 仅为示例,非真实的接口地址 filePath: url, name: 'file', formData: { OSSAccessKeyId: " ", //Bucket拥有者的AccessKey ID默认值:无 policy: " ", //当Bucket为非public-read-write或者提供了OSSAccessKeyId(或Signature)表单域时,必须提供Policy表单域。 Signature: " ", //AccessKey Secret和Policy计算的签名信息 host: " ", //直传oss的服务器地址 dir: this.usercodes + "/prop/pic/", //上传oss文件路径+文件名 success_action_status: 200, //该表单域指定了上传成功后返回给客户端的状态码。该表单域指定了上传成功后返回给客户端的状态码。 key: this.usercodes + "/prop/pic/" + nameurl, //上传Object的名称 上传oss文件路径+文件名 },
-
上传成功