OSS 上传的操作

OSS 上传的操作:

依赖包:

        
            com.aliyun.oss
            aliyun-sdk-oss
            3.15.1
        
配置文件:
#阿里
aliyun.sms.accessKeyId=LTAI5tMxsuT67msinBp31254
aliyun.sms.accessKeySecret=zDJW1i4Rq3nbTKb31A8ycfrKM6b14
aliyun.sms.templateCode=SMS_464506225
#阿里OSS
aliyun.oss.bcketName=gulimall-vues
aliyun.oss.urlprefix=http://gulimall-vues.oss-cn-chengdu.aliyuncs.com/
aliyun.oss.endpoint=http://oss-cn-chengdu.aliyuncs.com
配置类:
package com.example.tanhuanapp.controller;

import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @author IT空门_门主
 * @date 2024/1/11
 */
@Configuration
@PropertySource("classpath:application.properties")
@Data
public class AliyunOssConfig {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bcketName}")
    private String bucketName;
    @Value("${aliyun.oss.urlprefix}")
    private String urlPrefix;

    /**
     * 将OSS注入容器
     * @return
     */
    @Bean
    public OSSClient ossClient(){
        return new OSSClient(endpoint,accessKeyId,accessKeySecret);
    }



}
实现类(仅供参考):
package com.example.tanhuanapp.server.impl;

import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSSClient;
import com.example.tanhuanapp.controller.AliyunOssConfig;
import com.example.tanhuanapp.pojo.vo.PicUploadResult;
import com.example.tanhuanapp.server.PicUploadServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
/**
 * @author IT空门_门主
 * @date 2024/1/11
 */

@Slf4j
@Service
public class PicUploadServerImpl  implements PicUploadServer {
    //允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".jpg", ".jpeg", ".bmp", ".png", ".gif"};
    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunOssConfig aliyunOssConfig;


    /**
     * 上传图片
     * @param uploadFile
     * @return
     */
    @Override
    public PicUploadResult upload(MultipartFile uploadFile) {
        log.info("传入的路径:{}",uploadFile);
        PicUploadResult fileUploadResult = new PicUploadResult();
         //图片做校验,对后缀名进行校验
        boolean isLegal = false;
        for (String type: IMAGE_TYPE ){
            if(StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)){
                isLegal =true;
                break;
            }
        }
        //为 false校验失败
        if(!isLegal){
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        //文件新路径
        String filename = uploadFile.getOriginalFilename();
        log.info("文件名:{}",filename);
        String filePath =getFilePath(filename);
        log.info("文件路径:{}",filePath);
        //上传到阿里云
        try {
            ossClient.putObject(aliyunOssConfig.getBucketName(),filePath,new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return  fileUploadResult;
        }
        //上传成功
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(this.aliyunOssConfig.getUrlPrefix()+filePath);
        log.info("OSS文件路径:{}",this.aliyunOssConfig.getUrlPrefix()+filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }

    /**
     * 处理图片路径
     * @param filename
     * @return
     */
    private String getFilePath(String filename) {
        DateTime dateTime = new DateTime();
        //生成文件名
        return "images/"+ dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd")
                +System.currentTimeMillis()+ RandomUtils.nextInt(100,9999)+"."+StringUtils.substringAfterLast(filename,".");


    }
}

测试结果:

OSS 上传的操作_第1张图片

你可能感兴趣的:(java,阿里云)