Spring Boot+Vue+阿里云OOS实现图片上传

网上的案例看了下,感觉可行,就自己改了一部分,补全了一部分,成功上传成功。

后端:

pom引入:

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.15.2</version>
        </dependency>

配置文件:

endPoint在你创建好的bucket的概览里面可以找到,accessKeyId和secretAccessKey是在授权管理里面生成

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OssClientConfig {

    @Bean
    public OSSClient createOssClient() {
        return (OSSClient)new OSSClientBuilder().build("你的对外访问的endPoint",
                "你的accessKeyId",
                "你的secretAccessKey");
    }
}

service:

import com.aliyun.oss.OSSClient;
import com.atguigu.ggkt.exception.GuiguException;
import com.atguigu.ggkt.vod.service.IOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@Service
public class IOssServiceImpl implements IOssService {

    @Autowired
    private OSSClient ossClient;

    @Override
    public String upload(MultipartFile file) {
        String bucketName = "你创建的bucket的名字";
        try {
            String objectName = getBucketName(file.getOriginalFilename());
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, file.getInputStream());
            return "https://" +bucketName+"."+ ossClient.getEndpoint().getHost() + "/" + objectName;
        } catch (IOException e) {
            throw new GuiguException(400,"上传失败");
        }
    }
    
    //图片格式,可以自己加
    private static final String[] imageExtension = new String[]{ ".jpg", ".jpeg",  ".png"};

    private String getBucketName(String url) {
        String ext = "";
        for(String extItem:imageExtension){
            if(url.contains(extItem)){
                ext = extItem;
                break;
            }
        }
        //日期将作为文件夹名,每天的图片会存到当天的文件夹内
        //文件名为uuid值
        return LocalDate.now() +"/"+ UUID.randomUUID() +ext;
    }
}

controller:

    @PostMapping(value = "/upload")
    @ApiOperation("上传")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)  {
        return Result.ok(ossService.upload(file)).message("文件上传成功");
    }

用postman测试了一下:

{
    "code": 20000,
    "message": "文件上传成功",
    "data": "https://xxxx-xxxxx.oss-cn-guangzhou.aliyuncs.com/2022-11-09/f845560f-6c95-41d4-8d85-e31deae3780c.png"
}

前端:

action的值就是上传的api接口

      <el-form-item label="讲师头像">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :on-error="handleAvatarError"
          :action="BASE_API+'/admin/vod/teacher/upload'"
          class="avatar-uploader"
        >
          <img v-if="teacher.avatar" :src="teacher.avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
methods: {
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      // console.log(res)
      if (res.code === 20000) {
        // console.log(res)
        this.teacher.avatar = res.data
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error('上传失败 (非0)')
      }
    },

    // 错误处理
    handleAvatarError() {
      console.log('error')
      this.$message.error('上传失败(http失败)')
    },

    // 上传校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 5

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值