vue + elementUi + upLoadIamge组件 上传文件到阿里云oss
<template> <div class="upLoadIamge"> <el-upload action="https://jsonplaceholder.typicode.com/posts/" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :http-request="myLoad" > <i class="el-icon-plus"></i> </el-upload> <el-dialog :visible.sync="dialogVisible"> <img width="100%" :src="dialogImageUrl" alt=""> </el-dialog> </div> </template>
<script> let axios = require('axios') export default { name: 'upLoadIamge', data () { return { dialogImageUrl: '', dialogVisible: false } }, methods: { handleRemove (file, fileList) { console.log(file, fileList) }, handlePictureCardPreview (file) { this.dialogImageUrl = file.url this.dialogVisible = true }, // 自定义上传的方式 作者:曾经的水哥 https://www.cnblogs.com/cengjingdeshuige/ myLoad (param) { let file = param.file // 得到文件的内容 console.log(file) let index = file.name.indexOf('.') let nameEnd = file.name.substr(index) const ossApiUrl = '这个是获取OSS签名的后台接口地址' // 获取oss签名的地址 // 获取oss签名 axios.post(ossApiUrl).then((data) => { if (data.status == 200 && data.data.code == 0) { //eslint-disable-line let json = data.data.data let ossUrl = json.host let nameStart = new Date().getTime() + '' + Math.ceil(Math.random() * 100) let name = '/' + nameStart + nameEnd let getUrl = json.host + '/' + json.dir + name // 上传后的文件地址 let sendData = new FormData() // 上传文件的data参数 sendData.append('OSSAccessKeyId', json.accessid) sendData.append('policy', json.policy) sendData.append('Signature', json.signature) sendData.append('keys', json.dir) sendData.append('key', json.dir + name) sendData.append('success_action_status', 200) // 指定返回的状态码 sendData.append('type', 'image/jpeg') sendData.append('file', file) console.log(sendData) axios.post(ossUrl, sendData).then(() => { console.log('得到上传到阿里云的图片地址: ' + getUrl) }) } }) } }, mounted () { } } </script>