首页 > 其他分享 >vue3引入ElementPlus实现OOS前端直传

vue3引入ElementPlus实现OOS前端直传

时间:2023-01-29 23:44:27浏览次数:61  
标签:ElementPlus String oss respMap OOS put import OSS 直传

1.1 开通OSS服务

登录阿里云官网;

将鼠标移至产品标签页,单击对象存储 OSS,打开OSS 产品详情页面;

在OSS产品详情页,单击立即开通。

1.2 后端整合OSS实现文件上传

在pom.xml中添加相关依赖

 <dependency>
     <groupId>com.aliyun.oss</groupId>
     <artifactId>aliyun-sdk-oss</artifactId>
     <version>3.15.1</version>
     </dependency>
 ​
     <dependency>
     <groupId>javax.xml.bind</groupId>
     <artifactId>jaxb-api</artifactId>
     <version>2.3.1</version>
     </dependency>
     <dependency>
     <groupId>javax.activation</groupId>
     <artifactId>activation</artifactId>
     <version>1.1.1</version>
     </dependency>
     <!-- no more than 2.3.3-->
     <dependency>
     <groupId>org.glassfish.jaxb</groupId>
     <artifactId>jaxb-runtime</artifactId>
     <version>2.3.3</version>
     </dependency>
     <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

创建OSSController类

 package com.tuling.controller;
 ​
 import com.aliyun.oss.OSS;
 import com.aliyun.oss.OSSClientBuilder;
 import com.aliyun.oss.common.utils.BinaryUtil;
 import com.aliyun.oss.model.MatchMode;
 import com.aliyun.oss.model.PolicyConditions;
 import org.springframework.web.bind.annotation.CrossOrigin;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 ​
 import java.text.SimpleDateFormat;
 import java.util.Date;
 import java.util.LinkedHashMap;
 import java.util.Map;
 ​
 /**
  * @author yang
  * @data 2023/1/28
  * @apiNote
  */
 @RestController
 @RequestMapping("/oss")
 public class OSSController {
 ​
     @CrossOrigin
     @RequestMapping("/policy")
     public Map<String, String> policy() {
         // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
         String accessId = "LTAI5t8LPUeZoN7ERDLGUatY";
         String accessKey = "r7ltwSx4shrqTK25vUC56f82H7WYl0";
         // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
         String endpoint = "oss-cn-hangzhou.aliyuncs.com";
         // 填写Bucket名称,例如examplebucket。
         String bucket = "tulingmall-yangyang";
         // 填写Host地址,格式为https://bucketname.endpoint。
         String host = "https://" + bucket + "." + endpoint;
         // 设置上传回调URL,即回调服务器地址,用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后,把文件上传信息通过此回调URL发送给应用服务器。
         //String callbackUrl = "https://192.168.0.0:8888";
         // 设置上传到OSS文件的前缀,可置空此项。置空后,文件将上传至Bucket的根目录下。
         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
         String date = simpleDateFormat.format(new Date());
         String dir = date + "/";
 ​
         // 创建ossClient实例。
         OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
         try {
             long expireTime = 30;
             long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
             Date expiration = new Date(expireEndTime);
             PolicyConditions policyConds = new PolicyConditions();
             policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
             policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
 ​
             String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
             byte[] binaryData = postPolicy.getBytes("utf-8");
             String encodedPolicy = BinaryUtil.toBase64String(binaryData);
             String postSignature = ossClient.calculatePostSignature(postPolicy);
 ​
             Map<String, String> respMap = new LinkedHashMap<String, String>();
             respMap.put("accessId", accessId);
             respMap.put("policy", encodedPolicy);
             respMap.put("signature", postSignature);
             respMap.put("dir", dir);
             respMap.put("host", host);
             respMap.put("expire", String.valueOf(expireEndTime / 1000));
             // respMap.put("expire", formatISO8601Date(expiration));
 ​
             //JSONObject jasonCallback = new JSONObject();
             //jasonCallback.put("callbackUrl", callbackUrl);
             //jasonCallback.put("callbackBody",
             //        "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
             //jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
             //String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
             //respMap.put("callback", base64CallbackBody);
 ​
             //JSONObject ja1 = JSONObject.fromObject(respMap);
             //// System.out.println(ja1.toString());
             //response.setHeader("Access-Control-Allow-Origin", "*");
             //response.setHeader("Access-Control-Allow-Methods", "GET, POST");
             //response(request, response, ja1.toString());
             return respMap;
         } catch (Exception e) {
             // Assert.fail(e.getMessage());
             System.out.println(e.getMessage());
         }
         return null;
     }
 }
 ​

1.3 前端整合ElementPlus实现文件上传

在main.js引入ElementPlus和axios

 import { createApp } from 'vue'
 import App from './App.vue'
 import router from './router'
 import store from './store'
 import ElementPlus from 'element-plus'
 import 'element-plus/es/components/button/style/css'
 ​
 import axios from 'axios'
 // import VueAxios from 'vue-axios'
 ​
 const app = createApp(App);
 app.use(store).use(router).use(ElementPlus).mount('#app')
 ​
 ​
 app.config.globalProperties.$axios = axios
 ​

在components中创建OssUpload.vue组件

 <template>
   <el-upload
     class="upload-demo"
     :action="ObjData.host"
     :file-list="fileList"
     :before-upload="ossPolicy"
     :data="ObjData"
     list-type="picture"
   >
     <el-button
       size="small"
       type="primary"
     >点击上传</el-button>
     <div class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
   </el-upload>
 </template>
 ​
 <script>
 export default {
   name: 'OssUpload',
   mixins: [],
   components: {},
   props: {},
   data () {
     return {
       fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}],
       ObjData: {
         OSSAccessKeyId: '',
         policy: '',
         Signature: '',
         key: '',
         host: '',
         dir: ''
       }
     }
   },
   computed: {},
   watch: {},
   created () {},
   mounted () {},
   methods: {
     ossPolicy(file) {
       // 上传前进行服务器签名
       return new Promise((resovle,reject)=>{
         // 请求后端
         this.$axios.get('http://localhost:8088/oss/policy')
         .then((res) => {
           this.ObjData.OSSAccessKeyId=res.data.accessId;
           this.ObjData.policy=res.data.policy;
           this.ObjData.Signature=res.data.signature;
           this.ObjData.host=res.data.host;
           this.ObjData.dir=res.data.dir;
           this.ObjData.key=res.data.dir+"${filename}";  
           resovle(true); // 继续上传
         })
         .catch((err) => {
           console.log(err);
           resovle(false);
         })
       })
     }
   }
 }
 </script>
 ​
 <style scoped lang="scss">
 </style>
 ​
 

 

 

 

标签:ElementPlus,String,oss,respMap,OOS,put,import,OSS,直传
From: https://www.cnblogs.com/LEPENGYANG/p/17074122.html

相关文章