前端上传图片到EOS

发布时间 2023-12-27 17:22:33作者: 洞庭府君

最近个人小项目中用到了移动云的EOS服务,需求是前端直接上传图片到移动云的EOS,将返回的图片URL作为参数传给后端,步骤如下:

1、安装依赖:cnpm i aws-sdk

2、指定访问权限:

 1 // 创建 plugins/aws.js 文件
 2 const AWS = require('aws-sdk')
 3 
 4 export const s3 = new AWS.S3({
 5     apiVersion: '2006-03-01',
 6     accessKeyId: 'your-access-key',
 7     secretAccessKey: 'your-secret-access-key',
 8     // endpoint 填写 bucket 所在地域的域名,本章节以 chengdu6 为例
 9     endpoint: 'eos-chengdu-6.cmecloud.cn', 
10     signatureVersion: 'v2',
11     sslEnabled: false
12 });
13 
14 export const bucket = 'your-bucket-name'

3、使用el-upload组件,上传beforeUpload中做文件类型、大小限制,截取file,上传文件:

 1 <template>
 2 <div class="img-uploader">
 3     <el-upload accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG" :before-upload="beforeUpload" />
 5 </div>
 6 </template
 8 
 9 import { s3, bucket } from '@/plugins/aws'
10 
11 methods: {
12     beforeUpload (file) {
13       const isImg = this.imageTypes.indexOf(file.type) !== -1
14       const isLt2M = file.size / 1024 < this.fileSize
15 
16       if (!isImg) {
17         this.$message.warning('图片格式不对!', 'error')
18         return
19       }
20       if (!isLt2M) {
21         this.$message.warning('图片大小不能超过 ' + this.fileSize / 1024 + 'MB!', 'error')
22         return
23       }
24       this.handleUpload(file)
25       return false
26     },
27     handleUpload (file) {
28       let params = {
29         Key: file.name + Date.now(),
30         Bucket: bucket,
31         ContentType: file.type,
32         Body: file,
33         ACL: 'public-read' //文件访问权限,参考:https://ecloud.10086.cn/op-help-center/doc/article/57954
34       }
35       s3.upload(params, (err, data) => {
36         if (err) {
37           this.$message.error('上传失败')
38         } else {
39           this.$emit('update', data.Location) // data.Location 为图片上传后的url
40         }
41       })
42     }
43 }