vue2使用elementui组件将图片从前端上传至阿里云oss

vue2使用elementui组件将图片从前端上传至阿里云oss

前端代码

<template>
    <div>
        <el-upload class="avatar-uploader" 
        action="/api/upload" //这里是必选参数,上传的地址
        :headers="headers"
        name="image"
        :show-file-list="false"
        :on-success="handleAvatarSuccess" 
        :before-upload="beforeAvatarUpload">
            
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
            
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</template>
<script>
import { getToken } from '@/utils/token';
// import { upload } from '@/utils/upload';
const options = {
    computed: {

    },
    mounted() {



    },
    methods: {
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }

    },
    data() {
        return {
            imageUrl: '',
            headers:{
                Authorization:  getToken()
            }
        }
    },
}
export default options;
</script>
<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

后端接收代码

阿里云提供的工具类

package com.novel.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.novel.pojo.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component//交给ioc容器管理
public class AliOSSUtils {
    /**
     * - @Value注解只能一个一个的进行外部属性的注入。
     *
     * - @ConfigurationProperties可以批量的将外部的属性配置注入到bean对象的属性中。
     */


    /**
     * 方法一:参数多的情况叫繁琐
     * @Value 注解通常用于外部配置的属性注入,具体用法为: @Value("${配置文件中的key}")
     * 将阿里云的配置文件读出来
     * @Value("${aliyun.oss.endpoint}")
     *
     * private String endpoint;
     * @Value("${aliyun.oss.accessKeyId}")
     * private String accessKeyId;
     *
     * @Value("${aliyun.oss.accessKeySecret}")
     * private String accessKeySecret;
     *
     * @Value("${aliyun.oss.bucketName}")
     * private String bucketName;
     */


    /**
     * 方法二:
     * 创建一个实体类,交给ioc容器管理
     * 在实体类上添加`@ConfigurationProperties`注解,并通过perfect属性来指定配置参数项的前缀
     * 然后将这个实体类注入进这个类中
     */
    @Autowired
    private AliOSSProperties aliOSSProperties;


    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(),aliOSSProperties.getAccessKeyId(),aliOSSProperties.getAccessKeySecret());
        ossClient.putObject(aliOSSProperties.getBucketName(), fileName, inputStream);

        //文件访问路径
        String url = aliOSSProperties.getEndpoint().split("//")[0] + "//" + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().split("//")[1] + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }
}

创建一个实体类,将交给ioc容器管理

/**
 * 方法二:
 * 创建一个实体类,交给ioc容器管理
 * 在实体类上添加`@ConfigurationProperties`注解,并通过perfect属性来指定配置参数项的前缀
 * 然后将这个实体类注入进这个类中
 */
 
package com.novel.pojo;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "aliyun.oss")//通过perfect属性来指定配置参数项的前缀
public class AliOSSProperties {
    //区域
    private String endpoint;
    //身份Id
    private String accessKeyId;
    //身份秘钥
    private String accessKeySecret;
    //储存空间
    private String bucketName;
}

创建 application.yml 配置文件

aliyun:
  oss:
    endpoint: xxx //区域
    accessKeyId: xxx //身份Id
    accessKeySecret: xxx //身份秘钥
    bucketName: xxx //储存空间

然后就可以将ioc注入到所需要的地方

package com.novel.controller;

import com.novel.pojo.Result;
import com.novel.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliOSSUtils aliOSSUtils;

    @PostMapping("/api/upload")
    public Result upload(MultipartFile image) throws IOException {
        //调用阿里云OSS工具类,将上传上来的文件存入阿里云
        String url = aliOSSUtils.upload(image);
        //将图片上传完成后的url返回,用于浏览器回显展示
        log.info("图片上传完成,{}",url);
        return Result.success(url);
    }
}
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: 在Vue使用ElementUI组件非常简单,只需要按照以下步骤即可: 1. 安装ElementUI:可以使用npm或yarn进行安装,命令如下: ``` npm install element-ui --save ``` 或者 ``` yarn add element-ui ``` 2. 在Vue项目中引入ElementUI:在main.js中引入ElementUI并注册组件,代码如下: ```javascript import Vue from 'vue' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) ``` 3. 在Vue组件使用ElementUI组件:在需要使用ElementUI组件Vue组件中,直接使用即可,例如: ```html <template> <div> <el-button type="primary">主要按钮</el-button> </div> </template> ``` 以上就是在Vue使用ElementUI组件的基本步骤,希望能对你有所帮助。 ### 回答2: Vue.js 是一个流行的前端 JavaScript 框架之一,而 Element UI 是面向 Web 开发者的开源 UI 框架。当这两个框架交汇在一起时,就可以创建易于维护和可扩展的 Vue.js 应用程序。 使用 Element UI 组件库可以大大加速 Vue.js 应用程序的开发过程。如果您使用 Element UI,您将能够在几分钟内构建出功能齐全的 UI 功能。它包含许多常用的组件,如表格,菜单,选项卡,表单和按钮。 使用 Element UI 组件库的第一步是在您的 Vue.js 应用程序中安装它。要使用 Element UI,您首先需要将它安装到您的项目中。您可以通过 npm(Node.js 包管理器)或 Yarn(快速可靠的依赖管理器)来完成此操作。 使用 npm 安装 ElementUI,需要在命令提示符下输入以下命令: ``` npm install element-ui -S ``` 如果您使用的是 Yarn,您可以使用以下命令: ``` yarn add element-ui ``` 一旦您安装了 ElementUI,您就可以在您的 Vue.js 应用程序中使用各种 ElementUI 组件了。您需要做的第一件事是将 ElementUI CSS 添加到您的页面中。您可以将以下代码添加到您的 index.html 文件中: ``` <link rel="stylesheet" href="//unpkg.com/element-ui/lib/theme-chalk/index.css"> ``` 接下来,在您的 Vue.js 组件中引入 ElementUI 组件,例如: ``` <template> <el-button type="primary">Click me!</el-button> </template> <script> import { Button } from 'element-ui' export default { name: 'MyComponent', components: { 'el-button': Button } } </script> ``` 这就是使用 Element UI 组件的基础知识。您可以添加其他组件来构建您的 Vue.js 应用程序,例如对话框,弹出式菜单,警告框等等。这些组件使您的应用程序看起来更专业,使用户体验更加友好。 ### 回答3: Vue.js是一款流行的前端框架,其主要特点是数据的响应式更新和简化了DOM操作。而Element UI是一个开源的基于Vue.js的UI组件库,它提供了一系列的常用组件,能够方便地构建出美观且高效的Web应用程序界面。这里我们来介绍一下如何在Vue.js中使用Element UI组件。 第一步:安装Element UI 我们可以通过npm或yarn来安装Element UI。 npm安装: npm i element-ui -S yarn安装: yarn add element-ui 第二步:引入Element UI 在我们的Vue项目中使用Element UI,需要先在Vue入口文件main.js引入它,并且使用Vue.use()注册它: import Vue from 'vue' import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI); 这里我们还需要注意,在引入Element UI时,也要同时引入Element UI的CSS样式文件。 第三步:使用Element UI组件 在以上步骤完成之后,我们就可以在vue使用Element UI组件了。例如,我们可以在template中使用组件el-button来创建一个按钮: <template> <div> <el-button type="primary">主要按钮</el-button> </div> </template> 这里我们需要注意的是,我们必须在script中引入el-button组件: <script> import { Button } from 'element-ui'; export default { components: { 'el-button': Button } } </script> 总结 以上就是在Vue使用Element UI组件的步骤,只需要三个简单的步骤就可以方便地使用Element UI组件,大大加快了我们构建Vue项目的开发效率。Element UI提供了丰富的组件库,可以满足我们在开发过程中的大部分需求,所以在项目中使用它也是非常不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农SUN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值