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

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

后端:

pom引入:

        
            com.aliyun.oss
            aliyun-sdk-oss
            3.15.2
        

配置文件:

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接口

      
        
          
          
        
      
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
    }
  }

你可能感兴趣的:(vue.js,spring,boot,阿里云)