Vue + Alioss前端上传图片

    技术2022-07-12  68

    Vue + Alioss前端上传图片

    准备工作安装依赖js工具类封装使用end

    准备工作

    需要注册一个ali云申请accesskeys,具体的操作请参考 link.

    安装依赖

    npm install ali-oss

    js工具类封装

    let OSS=require('ali-oss'); let client=new OSS({ accessKeyId: '你创建的Bucket时获取的' accessKeySecret: ' 你创建的Bucket时获取的' bucket: '你创建的Bucket名称' region: 'oss-cn-shenzhen' // 你所购买oss服务的区域,默认oss-cn-hangzhou }) // 上传 export async function put (filePath, file) { try { return await client.put(filePath, file) } catch (err) { console.log(err) } } // 删除 export async function remove (filePath) { try { return await client.delete(filePath) } catch (err) { console.log(err) } }

    使用

    import { client, put, remove } from '@/utils/alioss' //页面html <el-upload list-type="picture" action="" accept="'image/*'" :http-request="upLoad" :on-remove="handleRemove" :before-upload="beforeUploadFile" :on-success="handleFileSuccess" :auto-upload="true" :file-list="imageValue" :limit="1"> <el-button size="small" type="primary">答案上传<i class="el-icon-upload el-icon--right"></i> </el-button> </el-upload> //js文件 beforeUploadFile(file){ const isLt10M = file.size / 1024 / 1024 < 10; if (!isLt10M) { this.$message.error("图片不能超过10M"); return false; } }, //文件上传成功的函数(用于文件上传成功之后的逻辑) handleFileSuccess(res, file,fileList){ }, upLoad (item) { // item 是当前本地上传的这张图片 // 随机命名 let fileName = item.file.name ; // 当前本地上传的这张图片的名称(没有时间日期) let date = new Date(); let year = date.getFullYear(); let month = date.getMonth() + 1; let day = date.getDay() + 1 ; let minutes = date.getMinutes() + 1; month = (month < 10 ? '0' + month : month); day = (day < 10 ? '0' + day : day); minutes = (minutes < 10 ? '0' + minutes : minutes); this.baseurl = 'exam/' + year + '/' + month + '/' + minutes + '/'; // 这里是把时间+图片名称拼接起来形成一个新的图片上传至oss,目的是区别于本地图片的名称,避免名称相同会误删,同时便于查看oss上最新上传图片的时间点 let filePath = this.baseurl + '-' + fileName let file = item.file; // 当前本地上传的这张图片 put(filePath, file).then(result => { // 调oss api 上传图片 // 文件上传成功后,获取返回值中的文件名name,并把其放入fileList数组中,表示当前已上传的文件 this.fileList.push(result.name) this.select[this.problemNumber] = result.url; this.$message.success('图片上传成功',); this.$emit('imageUrl',result) }).catch(e=>{ this.$message.error('图片上传失败'+e); }) }, handleRemove (file) { // file 当前本地已上传的这张图片 let fileName = file.name // 当前本地已上传的这张图片的名称(带有时间日期) let removeName = '' this.fileList.forEach(function (name) { // forEach 在循环的数组中(fileList)找到oss和本地相同的文件名称 if (name.match(fileName)) { removeName = name // 给循环出匹配上文件名的name赋值,这里循环出的图片是带有时间日期 } }) remove(removeName).then(result => { // 把循环出来的图片传进来,然后进行删除 console.log(result) if (result.res.status !== 204) { this.$message.error('图片删除失败'+result.res.status); }else{ this.select[this.problemNumber] = ''; this.paper.subjects[this.problemNumber].status = false; this.answerCount -= 1; this.$message({ message: '图片删除成功', type: 'success' }) this.$emit('imageUrl','') } }).catch(e=>{ this.$message.error('图片删除失败'+e); }) }

    end

    Processed: 0.014, SQL: 9