上传文件到 阿里云

  作者:chrispy

<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script><el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="PicsUpload"

<script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-4.4.4.min.js"></script>

<el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="PicsUpload" :before-upload="beforeAvatarUpload">

<img v-if="imageUrl" :src="imageUrl" class="avatar">

<i v-else class="el-icon-plus avatar-uploader-icon"></i>

</el-upload>

data () {

return {

imageUrl: '',

      client: ''

}

}

// 获取阿里云权限

getAliyunToken () {

this.$axios.get('/iCloud-rest/projects/Aliyun/token/').then(res => {

const result = res.data.data

const status = res.data.status

if (status === 200) {

this.client = new window.OSS.Wrapper({

accessKeyId: result.accessKeyId,

secure: true,

accessKeySecret: result.accessKeySecret,

stsToken: result.stsToken,

region: 'oss-cn-beijing',

bucket: result.bucket

})

} else if (result.code !== 200 && result.code !== 401) {

this.$message.error(result.message)

}

})

},

PicsUpload (param) { // 上传图片 - 登陆页面图

let timeStamp = new Date().getTime()

try {

let pattern = 'images/' + timeStamp + '.jpg'

let file = param.file

if (file !== undefined) {

this.client.multipartUpload(pattern, file).then((result) => {

let httpSrc = result.url

if (httpSrc.indexOf('?') !== -1) {

httpSrc = httpSrc.substr(0, httpSrc.indexOf('?'))

}

this.imageUrl = httpSrc

}).catch(() => {

this.$message({

type: 'info',

message: '图片选取上传失败,请重新选择上传!!'

})

})

}

} catch (ex) {

}

},

beforeAvatarUpload (file) {

const isJPEG = file.type === 'image/jpeg'

const isPNG = file.type === 'image/png'

const isGIF = file.type === 'image/gif'

const isLt5M = file.size / 1024 / 1024 < 5

if (!isJPEG && !isPNG && !isGIF) {

this.$message.error('上传图片只能是 JPG、PNG、GIF 格式!')

return false && isLt5M

} else if (!isLt5M) {

this.$message.error('上传图片大小不能超过 5MB!')

return false && isLt5M

} else if (isJPEG) {

return isJPEG && isLt5M

} else if (isPNG) {

return isPNG && isLt5M

} else if (isGIF) {

return isGIF && isLt5M

}

},


有用  |  无用

猜你喜欢