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

这是一个上传小dome。可以用。但是很多要更具实际结合系统优化。

 

 

1.架包



   com.aliyun.oss
   aliyun-sdk-oss
   2.4.0


   commons-fileupload
   commons-fileupload
   1.3.1

2 spring boot 基于.yml的配置

  # OSS配置
images-roland:
    file:
      endpoint: https://xxxxxxxx.com
      keyid: xxxx
      keysecret : xxxxxx
      bucketname : xxxxxx
      #目标文件夹
      filehost : xxxxxImages/
      #显示域名头地址
      show_image_host : xxxxxxxxx.com

 

3. config 配置

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

/*
* 阿里云文件服务器config
*
* */
@Configuration
public class AliyunOSSConfig {
    private OSSClient ossClient;

    @Value("${images-roland.file.endpoint}")
    private String endpoint;

    @Value("${images-roland.file.keyid}")
    private String accessKeyId;

    @Value("${images-roland.file.keysecret}")
    private String secretAccessKey;

    @Value("${images-roland.file.filehost}")
    private String fileHost;

    @Value("${images-roland.file.bucketname}")
    private String bucketName;


    @Value("${images-roland.file.show_image_host}")
    private String show_image_host;




    @Bean("ossClients")
    public OSSClient ossClient(){
        return new OSSClient(endpoint,accessKeyId,secretAccessKey);
    }

    public String getFileHost() {
        return fileHost;
    }

    public void setFileHost(
            String fileHost
    ) {
        this.fileHost = fileHost;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(
            String bucketName
    ) {
        this.bucketName = bucketName;
    }

    public String getShow_image_host() {
        return show_image_host;
    }

    public void setShow_image_host(String show_image_host) {
        this.show_image_host = show_image_host;
    }
}

 

 

4 uilt 工具类

 

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.framework.config.AliyunOSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Created by
 * Date 2018/2/7
 * Description:aliyunOSSUtil
 */
@Component
public class AliyunOSSUtil {

    private static OSSClient ossClients;
    @Autowired
    public AliyunOSSUtil(OSSClient ossClients) {
        AliyunOSSUtil.ossClients = ossClients;
    }
    @Autowired
    private  AliyunOSSConfig aliyunOSSConfig;

    public  String upload(File file){
      //  log.info("=========>OSS文件上传开始:"+file.getName());
//        System.out.println(ossClients);
        String bucketName = aliyunOSSConfig.getBucketName();
        String fileHost = aliyunOSSConfig.getFileHost();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return "";
        }

        OSSClient ossClient = ossClients;
       // System.out.println(ossClient);
        try {
            //容器不存在,就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                System.err.println("==========>OSS文件上传成功,OSS地址:"+fileUrl);
                // 加显示域名头
                return aliyunOSSConfig.getShow_image_host()+"/"+fileUrl;
            }
        }catch (OSSException oe){
            System.err.println(oe.getMessage());

        }catch (ClientException ce){
            System.err.println(ce.getMessage());

        }finally {
            //关闭
//            ossClient.shutdown();
        }
        return null;
    }
    public static String uploads(File file){
        AliyunOSSConfig aliyunOSSConfig = new AliyunOSSConfig();
        String bucketName = aliyunOSSConfig.getBucketName();
        String fileHost = aliyunOSSConfig.getFileHost();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }
//        OSSClient ossClient = ossClients;

        // 创建OSSClient实例。
        OSSClient ossClient = ossClients;
        String fileUrl = fileHost+"/"+(dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
        try {
            // 带进度条的上传。
            ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, new FileInputStream(file)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。
//        ossClient.shutdown();
        return null;
    }
}

 

5.Controller调用

@Autowired
private AliyunOSSUtil aliyunOSSUtil;

@PostMapping("/uploadCustomized")
@ResponseBody
private AjaxResult upload(@RequestParam("avatarfile") MultipartFile file) throws IOException {
    AjaxResult ajaxResult = new AjaxResult();

    File toFile = null;
    if(file.equals("")||file.getSize()<=0){
        file = null;
    }else {
        InputStream ins = null;
        ins = file.getInputStream();
        toFile = new File(file.getOriginalFilename());
        inputStreamToFile(ins, toFile);
        ins.close();
    }

    String surl =  aliyunOSSUtil.upload(toFile);
    ajaxResult.put("msg"," Upload succeeded !");
    ajaxResult.put("code",200);
    ajaxResult.put("url",surl);
    return ajaxResult;

}

/*  MultipartFile   to   File*/
public static void inputStreamToFile(InputStream ins, File file) {
    try {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

借鉴了大佬的代码

https://www.cnblogs.com/rolandlee/p/10513106.html

 

 

你可能感兴趣的:(SpringBoot-实现图片上传dome | 阿里云OSS)