vue3+element plus文件上传阿里云oss,文件无需经过服务器

优点

使用文件直传oss服务器的方式可以加快上传的速度,节约后端网络资源但是如果不设置上传认证的话容易导致服务器被恶意上传文件,所以使用后端服务器生成授权信息,授权的信息与上传的路径相关,客户端只能往服务器授权的路径上传文件,可以保证不被随便上传文件。

后端代码(java)

pom.xml

添加依赖

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.15.0</version>
        </dependency>
OssController.java
package com.qc.controller;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @author qc
 * @version 1.0
 * @date 2022/11/03 22:52
 */
@RestController
@RequestMapping("/oss")
public class OssController {

    @Value("${aliOss.endpoint}")
    private String endpoint;
    @Value("${aliOss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliOss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliOss.bucketName}")
    private String bucketName;


    /**
     * 获取阿里云oss文件上传链接
     *
     * @return java.lang.String 文件上传链接
     * @author qc
     * @date 2022/11/3 22:52
     */
    @GetMapping("/generatePresignedUrl")
    public String generatePresignedUrlRequest() {
        OSSClientBuilder ossClientBuilder = new OSSClientBuilder();
        OSS oss = ossClientBuilder.build(endpoint, accessKeyId, accessKeySecret);

//        文件名,可自行修改生成方式
        String key = UUID.randomUUID().toString();

//        授权过期时间
        Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 24L);

        GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.PUT);
        generatePresignedUrlRequest.setContentType("application/octet-stream");
        generatePresignedUrlRequest.setExpiration(expiration);

        URL url = oss.generatePresignedUrl(generatePresignedUrlRequest);
        return url.toString();
    }


}

前端代码(vue)

request.js
import axios from 'axios'

export default axios

ossApi.js
import request from "@/api/request.js";

export function generatePresignedUrlApi(params) {
    return request({
        url: '/oss/generatePresignedUrl',
        method: 'get',
        params:params,
    })
}

export function ossUploadApi(url,file,progressEvent) {
    return request({
        url: url,
        method: 'put',
        headers: {
            "Content-Type": "application/octet-stream"
        },
        data:file,
        onUploadProgress:progressEvent,
    })
}
Upload.vue
<template>
  <div>
    <el-upload
        :show-file-list="false"
        :http-request="uploadImg"
    >
      <img v-if="imageUrl" :src="imageUrl" style="width: 100px"/>
      <el-icon v-else style="margin-left: 60px">
        <el-button type="primary">选择图片</el-button>
      </el-icon>
    </el-upload>
  </div>
</template>

<script setup>

import {ref} from 'vue'
import {generatePresignedUrlApi, ossUploadApi} from "@/api/ossApi";

let imageUrl = ref(null)

const uploadImg = (file) => {
  generatePresignedUrlApi().then(res => {
    ossUploadApi(res.data.data, file.file, (progressEvent) => {
      console.log(progressEvent)
    }).then(r => {
      console.log(r);
      imageUrl.value = res.data.data.split("?")[0]
    })
  })
}

</script>

<style scoped>

</style>

如果文章可以给您提供帮助,还请帮忙点个小小的赞 

Logo

前往低代码交流专区

更多推荐