SpringBoot-实现图片上传 | 阿里云OSS

准备工作

  1. 准备一个云主机。
    云主机不一定要使用阿里云,只是最近疫情期间,阿里云有活动,学生可以免费用6个月,我今早定了闹钟7点50就起来抢这个免费的云主机了

  2. 开通OSS
    使用OSS教程文件

  3. 创建bucketSpringBoot-实现图片上传 | 阿里云OSS

编码部分

java中实现上传的教程参考:https://help.aliyun.com/document_detail/32013.html?spm=a2c4g.11186623.2.22.2abb7815PJ5Nce#concept-32013-zh

  1. 引入依赖
<!--阿里云-->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.8.1</version>
        </dependency>
  1. 必备参数配置
aliyun.bucketName=ju***nity
aliyun.accessKeyId=LT***9hs
aliyun.accessKeySecret=r7c***XF
aliyun.endpoint=http://oss-cn-shenzhen.aliyuncs.com
#目标文件夹
aliyun.filehost=userImg/
  1. 创建OSS工具类
package com.july.community.provider;

/**
 * 阿里云oss服务器工具类
 */
@Component
public class OssUtil {

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

    //文件存储目录
    @Value("${aliyun.filehost}")
    private String filedir;

    //上传图片
    public String uploadImg20ss(MultipartFile file){
        if (file.getSize() > 1024 * 1024 * 20){
            throw new CustomizeException(CustomizeErrorCode.IMAGE_TOO_MAX);
        }
        String originalFilename = file.getOriginalFilename();
        String subString = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name=random.nextInt(10000)+System.currentTimeMillis()+subString;
        try{
            InputStream inputStream = file.getInputStream();
            this.uploadFile20SS(inputStream,name);
            return  name;
        }catch (Exception e){
            throw new CustomizeException(CustomizeErrorCode.IMAGE_UPLOAD_FAIL);
        }
    }

    //上传图片获取fileUrl
    private String uploadFile20SS(InputStream instream,String fileName){
        String ret="";
        try {
            //创建上传object的Metadata
            ObjectMetadata objectMetadata=new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma","no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename="+fileName);
            //上传文件
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putRequest = ossClient.putObject(bucketName,filedir+fileName,instream,objectMetadata);
            ret=putRequest.getETag();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }finally {
            try{
                if (instream != null){
                    instream.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return ret;
    }

    //
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    //获取图片路径
    public String getImgUrl(String fileUrl){
        if (!StringUtils.isEmpty(fileUrl)){
            String[] split =fileUrl.split("/");
            String url=this.getUrl(this.filedir+split[split.length-1]);
            return url;
        }
        return null;
    }

    //获取url链接
    public String getUrl(String key){
        //设置Url过期时间为10年
        Date expiration =new Date(new Date().getTime() + 36001 * 1000 * 24 * 365 * 10);
        //生成URL
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        URL url=ossClient.generatePresignedUrl(bucketName,key,expiration);
        if (url != null){
            return url.toString();
        }
        return null;
    }

    //多图上传
    public String checkList(List<MultipartFile> fileList){
        String fileUrl="";
        String str = "";
        String photoUrl = "";
        for (int i =0;i<fileList.size();i++){
            fileUrl = uploadImg20ss(fileList.get(i));
            str = getImgUrl(fileUrl);
            if (i==0){
                photoUrl = str;
            }else {
                photoUrl+=","+str;
            }

        }
        return photoUrl.trim();
    }

    //单个图片上传
    public String checkImage(MultipartFile file){
        String fileUrl = uploadImg20ss(file);
        String str = getImgUrl(fileUrl);
        return str.trim();
    }



}

  1. FileController
package com.july.community.controller;

@Controller
public class FileController {

    @Autowired
    private FileService fileService;

    @RequestMapping("/file/upload")
    @ResponseBody
    private FileDTO upload(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("editormd-image-file");

        FileDTO fileDTO = fileService.fileUpload(file);
        return fileDTO;

    }
}

  1. FileService
package com.july.community.service;

@Service
public class FileService {
    @Autowired
    private OssUtil ossUtil;

    public FileDTO fileUpload(MultipartFile file) {
        if (file == null){
            throw new CustomizeException(CustomizeErrorCode.FILE_IS_EMPTY);
        }
        //上传
        String url=ossUtil.checkImage(file);
        //获取url
        FileDTO fileDTO = new FileDTO();
        fileDTO.setUrl(url);
        fileDTO.setSuccess(1);
        System.out.println(url);
        return fileDTO;

    }
}

遇坑

  1. 有一次上传,提示没权限。经过百度,发现,原来要给用户授权SpringBoot-实现图片上传 | 阿里云OSS
SpringBoot-实现图片上传 | 阿里云OSSSpringBoot-实现图片上传 | 阿里云OSS 秃顶少女 发布了34 篇原创文章 · 获赞 10 · 访问量 3114 私信 关注
上一篇:equals与equalsIgnoreCase


下一篇:架构还是转到前后端分离,并且实现了多租户支持