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


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

    后端:

    pom引入:

    1. <dependency>
    2. <groupId>com.aliyun.oss</groupId>
    3. <artifactId>aliyun-sdk-oss</artifactId>
    4. <version>3.15.2</version>
    5. </dependency>

    配置文件:

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

    1. import com.aliyun.oss.OSSClient;
    2. import com.aliyun.oss.OSSClientBuilder;
    3. import org.springframework.context.annotation.Bean;
    4. import org.springframework.context.annotation.Configuration;
    5. @Configuration
    6. public class OssClientConfig {
    7. @Bean
    8. public OSSClient createOssClient() {
    9. return (OSSClient)new OSSClientBuilder().build("你的对外访问的endPoint",
    10. "你的accessKeyId",
    11. "你的secretAccessKey");
    12. }
    13. }

    service:

    1. import com.aliyun.oss.OSSClient;
    2. import com.atguigu.ggkt.exception.GuiguException;
    3. import com.atguigu.ggkt.vod.service.IOssService;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.stereotype.Service;
    6. import org.springframework.web.multipart.MultipartFile;
    7. import java.io.IOException;
    8. import java.time.LocalDate;
    9. import java.util.UUID;
    10. @Service
    11. public class IOssServiceImpl implements IOssService {
    12. @Autowired
    13. private OSSClient ossClient;
    14. @Override
    15. public String upload(MultipartFile file) {
    16. String bucketName = "你创建的bucket的名字";
    17. try {
    18. String objectName = getBucketName(file.getOriginalFilename());
    19. // 创建PutObject请求。
    20. ossClient.putObject(bucketName, objectName, file.getInputStream());
    21. return "https://" +bucketName+"."+ ossClient.getEndpoint().getHost() + "/" + objectName;
    22. } catch (IOException e) {
    23. throw new GuiguException(400,"上传失败");
    24. }
    25. }
    26. //图片格式,可以自己加
    27. private static final String[] imageExtension = new String[]{ ".jpg", ".jpeg", ".png"};
    28. private String getBucketName(String url) {
    29. String ext = "";
    30. for(String extItem:imageExtension){
    31. if(url.contains(extItem)){
    32. ext = extItem;
    33. break;
    34. }
    35. }
    36. //日期将作为文件夹名,每天的图片会存到当天的文件夹内
    37. //文件名为uuid值
    38. return LocalDate.now() +"/"+ UUID.randomUUID() +ext;
    39. }
    40. }

    controller:

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

    postman测试了一下:

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

    前端:

    action的值就是上传的api接口

    1. <el-form-item label="讲师头像">
    2. <el-upload
    3. :show-file-list="false"
    4. :on-success="handleAvatarSuccess"
    5. :before-upload="beforeAvatarUpload"
    6. :on-error="handleAvatarError"
    7. :action="BASE_API+'/admin/vod/teacher/upload'"
    8. class="avatar-uploader"
    9. >
    10. <img v-if="teacher.avatar" :src="teacher.avatar">
    11. <i v-else class="el-icon-plus avatar-uploader-icon" />
    12. el-upload>
    13. el-form-item>
    1. methods: {
    2. // 上传成功回调
    3. handleAvatarSuccess(res, file) {
    4. // console.log(res)
    5. if (res.code === 20000) {
    6. // console.log(res)
    7. this.teacher.avatar = res.data
    8. // 强制重新渲染
    9. this.$forceUpdate()
    10. } else {
    11. this.$message.error('上传失败 (非0)')
    12. }
    13. },
    14. // 错误处理
    15. handleAvatarError() {
    16. console.log('error')
    17. this.$message.error('上传失败(http失败)')
    18. },
    19. // 上传校验
    20. beforeAvatarUpload(file) {
    21. const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
    22. const isLt2M = file.size / 1024 / 1024 < 5
    23. if (!isJPG) {
    24. this.$message.error('上传头像图片只能是 JPG/PNG/JPEG 格式!')
    25. }
    26. if (!isLt2M) {
    27. this.$message.error('上传头像图片大小不能超过 5MB!')
    28. }
    29. return isJPG && isLt2M
    30. }
    31. }

  • 相关阅读:
    想要顺利拿下订单,外贸人的价格谈判思维你GET了吗?
    微软TTS最新模型,发布9种更真实的AI语音
    App Store 发布应用过程,xcode打包
    java计算机毕业设计技术交流网站源码+数据库+系统+lw文档+mybatis+运行部署
    微服务·架构组件之服务注册与发现-Nacos
    js判断参数是否为空方法
    2023年【危险化学品生产单位安全生产管理人员】及危险化学品生产单位安全生产管理人员模拟考试题
    借助Web3盘活日本优质IP:UneMeta 与 OpenSea 的差异化竞争
    Java输入/输出之RandomAccessFile的功能和用法
    Docker 命令详解:容器、镜像、网络和数据卷管理
  • 原文地址:https://blog.csdn.net/xushuai2333333/article/details/127770915