阿里云OSS上传文件并返回文件地址

目录

依赖添加

实体类:

OSS配置类:

OSSUtil工具类:

OSS上传接口类:

OSS上传接口实现类:

OSS上传控制类:

工具类:


 

依赖添加

Maven的pom.xml文件中添加OSS的依赖:

  1.  
    <!--阿里云OSS-->
  2.  
    <dependency>
  3.  
    <groupId>com.aliyun.oss</groupId>
  4.  
    <artifactId>aliyun-sdk-oss</artifactId>
  5.  
    <version>2.8.3</version>
  6.  
    </dependency>

在application.yml中添加配置信息:

  1.  
    #OSS配置
  2.  
    oss:
  3.  
    #带有地域节点的请求地址
  4.  
    endpoint: oss-cn-beijing.aliyuncs.com
  5.  
    #阿里云用户id
  6.  
    accessKey: XXXXXXRnmzC2aafr9KXXXXXX
  7.  
    #阿里云用户密码
  8.  
    secretKey: XXXXXXFBaNzv85rqiks804mGXXXXXX
  9.  
    #阿里云存储空间名
  10.  
    bucketname: home
  11.  
    #阿里服务器的域名
  12.  
    fileHost: http://home.oss-cn-beijing.aliyuncs.com/
  13.  
    #上传文件路径
  14.  
    filePath: upload

实体类:

  1.  
    import lombok.Data;
  2.  
     
  3.  
    /**
  4.  
    * @author CYY
  5.  
    * @date 2022/4/15 16:52
  6.  
    */
  7.  
    @Data
  8.  
    public class OssData {
  9.  
    /**
  10.  
    * 服务器域名
  11.  
    */
  12.  
    private String host;
  13.  
    /**
  14.  
    * 上传文件路径
  15.  
    */
  16.  
    private String path;
  17.  
    /**
  18.  
    * 上传文件名
  19.  
    */
  20.  
    private String fileName;
  21.  
    }

OSS配置类:

  1.  
    import com.aliyun.oss.OSSClient;
  2.  
    import org.springframework.beans.factory.annotation.Value;
  3.  
    import org.springframework.context.annotation.Bean;
  4.  
    import org.springframework.context.annotation.Configuration;
  5.  
     
  6.  
    /**
  7.  
    * OSS配置类
  8.  
    *
  9.  
    * @author CYY
  10.  
    * @date 2022/4/15 16:20
  11.  
    */
  12.  
    @Configuration
  13.  
    public class OSSClientConfig {
  14.  
     
  15.  
    @Value("${oss.endpoint}")
  16.  
    String endpoint;
  17.  
    @Value("${oss.accessKey}")
  18.  
    String accessKeyId;
  19.  
    @Value("${oss.secretKey}")
  20.  
    String accessKeySecret;
  21.  
     
  22.  
    // 创建OSS客户端Bean
  23.  
    @Bean
  24.  
    public OSSClient getOSSClient() {
  25.  
    return new OSSClient(endpoint, accessKeyId, accessKeySecret);
  26.  
    }
  27.  
    }

OSSUtil工具类:

  1.  
    import com.aliyun.oss.ClientException;
  2.  
    import com.aliyun.oss.OSSClient;
  3.  
    import com.aliyun.oss.OSSException;
  4.  
    import com.aliyun.oss.model.CannedAccessControlList;
  5.  
    import com.aliyun.oss.model.CreateBucketRequest;
  6.  
    import com.aliyun.oss.model.PutObjectRequest;
  7.  
    import com.aliyun.oss.model.PutObjectResult;
  8.  
    import lombok.extern.log4j.Log4j2;
  9.  
    import org.springframework.beans.factory.annotation.Value;
  10.  
    import org.springframework.stereotype.Component;
  11.  
     
  12.  
    import javax.annotation.Resource;
  13.  
    import java.io.File;
  14.  
     
  15.  
    /**
  16.  
    * 阿里OSS工具类
  17.  
    *
  18.  
    * @author CYY
  19.  
    * @date 2022/4/15 16:23
  20.  
    */
  21.  
    @Component
  22.  
    @Log4j2
  23.  
    public class AliyunOSSUtil {
  24.  
    @Value("${oss.bucketname}")
  25.  
    String bucketName;
  26.  
    @Resource
  27.  
    private OSSClient client;
  28.  
     
  29.  
    /**
  30.  
    * 上传文件
  31.  
    */
  32.  
    public String upLoad(File file, String fileUrl) {
  33.  
    log.info("------OSS文件上传开始--------" + file.getName());
  34.  
    // 判断文件是否为空
  35.  
    if (file == null) {
  36.  
    return null;
  37.  
    }
  38.  
     
  39.  
    try {
  40.  
    // 判断容器是否存在,不存在就创建
  41.  
    if (!client.doesBucketExist(bucketName)) {
  42.  
    client.createBucket(bucketName);
  43.  
    CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
  44.  
    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
  45.  
    client.createBucket(createBucketRequest);
  46.  
    // 设置权限(公开读)
  47.  
    client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
  48.  
    }
  49.  
    // 上传文件
  50.  
    PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
  51.  
    if (result != null) {
  52.  
    log.info("------OSS文件上传成功------" + fileUrl);
  53.  
    return fileUrl;
  54.  
    }
  55.  
    } catch (OSSException oe) {
  56.  
    log.error(oe.getMessage());
  57.  
    } catch (ClientException ce) {
  58.  
    log.error(ce.getErrorMessage());
  59.  
    } finally {
  60.  
    }
  61.  
    return null;
  62.  
    }
  63.  
    }
  64.  
     

OSS上传接口类:

  1.  
    import org.springframework.web.multipart.MultipartFile;
  2.  
     
  3.  
    /**
  4.  
    * @author CYY
  5.  
    * @date 2022/4/15 16:42
  6.  
    */
  7.  
     
  8.  
    public interface OssUploadService {
  9.  
     
  10.  
    /**
  11.  
    * 上传文件
  12.  
    * @param file
  13.  
    * @return
  14.  
    */
  15.  
    String upload(MultipartFile file);
  16.  
    }

OSS上传接口实现类:

  1.  
    import jnpf.service.OssUploadService;
  2.  
    import jnpf.utils.AliyunOSSUtil;
  3.  
    import org.springframework.beans.factory.annotation.Autowired;
  4.  
    import org.springframework.beans.factory.annotation.Value;
  5.  
    import org.springframework.stereotype.Service;
  6.  
    import org.springframework.web.multipart.MultipartFile;
  7.  
     
  8.  
    import java.io.File;
  9.  
    import java.io.FileOutputStream;
  10.  
    import java.text.SimpleDateFormat;
  11.  
    import java.util.Date;
  12.  
     
  13.  
    /**
  14.  
    * @author CYY
  15.  
    * @date 2022/4/15 16:43
  16.  
    */
  17.  
    @Service
  18.  
    public class OssUploadServiceImpl implements OssUploadService {
  19.  
     
  20.  
    private final AliyunOSSUtil aliyunOSSUtil;
  21.  
     
  22.  
    @Autowired
  23.  
    public OssUploadServiceImpl(AliyunOSSUtil aliyunOSSUtil){
  24.  
    this.aliyunOSSUtil = aliyunOSSUtil;
  25.  
    }
  26.  
     
  27.  
    @Value("${oss.filePath}")
  28.  
    private String filePath;
  29.  
     
  30.  
    @Override
  31.  
    public String upload(MultipartFile file) {
  32.  
    // 返回客户端文件系统中的原始文件名
  33.  
    String fileName = file.getOriginalFilename();
  34.  
    System.out.println(fileName);
  35.  
     
  36.  
    try{
  37.  
    if (file != null) {
  38.  
    // 判定文件名是否为 ""
  39.  
    if (!"".equals(fileName.trim())) {
  40.  
    File newFile = new File(fileName);
  41.  
    FileOutputStream os = new FileOutputStream(newFile);
  42.  
    // 以字节数组的形式返回文件的内容,再输出到文件输出流中
  43.  
    os.write(file.getBytes());
  44.  
    os.close();
  45.  
    // 将接受的文件传输到给定的目标文件 file-->newFile
  46.  
    file.transferTo(newFile);
  47.  
    // 根据不同文件 类型/日期 生成不同的文件夹
  48.  
    Date date = new Date();
  49.  
    //String datePath = DateUtils.formatDateByStyle(date, DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());
  50.  
    String datePath = getCode().toString();
  51.  
    String timeStamp = String.valueOf(System.currentTimeMillis());
  52.  
    fileName = timeStamp + fileName.substring(fileName.lastIndexOf("."));
  53.  
    String path;
  54.  
    if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
  55.  
    // images
  56.  
    path = filePath + "/images/" + datePath + "/" + fileName;
  57.  
    } else {
  58.  
    path = filePath + "/other/" + datePath + "/" + fileName;
  59.  
    }
  60.  
    // 上传到OSS
  61.  
    String uploadUrl = aliyunOSSUtil.upLoad(newFile, path);
  62.  
    newFile.delete();
  63.  
    if (uploadUrl != null) {
  64.  
    return uploadUrl;
  65.  
    }
  66.  
    }
  67.  
    }
  68.  
    }catch (Exception e){
  69.  
    e.printStackTrace();
  70.  
    }
  71.  
    return null;
  72.  
    }
  73.  
     
  74.  
    /**
  75.  
    * 生成编号
  76.  
    *
  77.  
    * @return code
  78.  
    */
  79.  
    private static Long getCode() {
  80.  
    //生成当前时间戳的ID
  81.  
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
  82.  
    String newDate = sdf.format(new Date());
  83.  
    //生成5位随机数
  84.  
    int randomNum = (int) ((Math.random() * 9 + 1) * 10000);
  85.  
    String result = String.valueOf(randomNum);
  86.  
    String s = newDate + result;
  87.  
    Long code = Long.parseLong(s);
  88.  
    return code;
  89.  
    }
  90.  
     
  91.  
    }
  92.  
     

OSS上传控制类:

  1.  
    import io.swagger.annotations.Api;
  2.  
    import io.swagger.annotations.ApiOperation;
  3.  
    import jnpf.base.ActionResult;
  4.  
    import jnpf.entity.OssData;
  5.  
    import jnpf.service.OssUploadService;
  6.  
    import org.springframework.beans.factory.annotation.Autowired;
  7.  
    import org.springframework.beans.factory.annotation.Value;
  8.  
    import org.springframework.web.bind.annotation.*;
  9.  
    import org.springframework.web.multipart.MultipartFile;
  10.  
     
  11.  
    import java.util.HashMap;
  12.  
    import java.util.List;
  13.  
    import java.util.Map;
  14.  
     
  15.  
    /**
  16.  
    * 阿里云OSS
  17.  
    *
  18.  
    * @author CYY
  19.  
    * @date 2022/4/15 16:53
  20.  
    */
  21.  
    @Api(tags = "阿里云OSS",value = "阿里云OSS")
  22.  
    @RestController
  23.  
    @RequestMapping("/api/file/oss")
  24.  
    public class OssUploadController {
  25.  
     
  26.  
    @Value("${oss.fileHost}")
  27.  
    String fileHost;
  28.  
     
  29.  
    @Autowired
  30.  
    private OssUploadService ossUploadService;
  31.  
     
  32.  
    /**
  33.  
    * 获取服务器的ip地址
  34.  
    *
  35.  
    * @return
  36.  
    */
  37.  
    @ApiOperation("获取服务器的ip地址")
  38.  
    @GetMapping("getHost")
  39.  
    public ActionResult getHost() {
  40.  
    OssData ossData = new OssData();
  41.  
    ossData.setHost(fileHost);
  42.  
    return ActionResult.success(ossData);
  43.  
    }
  44.  
     
  45.  
    /**
  46.  
    * oss上传文件(单个文件上传)
  47.  
    *
  48.  
    * @param file
  49.  
    * @return
  50.  
    */
  51.  
    @ApiOperation("oss上传文件(单个文件上传)")
  52.  
    @PostMapping("fileUpload")
  53.  
    public ActionResult fileUpload(@RequestParam("file") MultipartFile file) {
  54.  
    OssData ossData = new OssData();
  55.  
    // 上传文件返回url
  56.  
    String url = ossUploadService.upload(file);
  57.  
    String fileName=url.substring(url.lastIndexOf("/")+1);
  58.  
    if (url != null) {
  59.  
    ossData.setHost(fileHost);
  60.  
    ossData.setPath(fileHost + url);
  61.  
    ossData.setFileName(fileName);
  62.  
    return ActionResult.success(ossData);
  63.  
    } else {
  64.  
    return ActionResult.fail(300, "上传失败");
  65.  
    }
  66.  
    }
  67.  
     
  68.  
    /**
  69.  
    * oss多文件上传
  70.  
    *
  71.  
    * @param files
  72.  
    * @return
  73.  
    */
  74.  
    @ApiOperation("oss多文件上传")
  75.  
    @PostMapping("filesUpload")
  76.  
    public ActionResult filesUpload(@RequestParam("file") List<MultipartFile> files) {
  77.  
    OssData ossData = new OssData();
  78.  
    Map<String, String> urls = new HashMap<>();
  79.  
    for (MultipartFile file : files) {
  80.  
    String url = ossUploadService.upload(file);
  81.  
    if (url != null) {
  82.  
    String fileName = file.getOriginalFilename();
  83.  
    url = fileHost + url;
  84.  
    urls.put(fileName, url);
  85.  
    } else {
  86.  
    ossData.setFileName(file.getOriginalFilename());
  87.  
    ossData.setPath(fileHost + url);
  88.  
    return ActionResult.fail(100, ossData, "上传失败");
  89.  
    }
  90.  
    }
  91.  
    return ActionResult.success(urls);
  92.  
    }
  93.  
     
  94.  
    /**
  95.  
    * oss 分俩个file,多文件上传
  96.  
    *
  97.  
    * @param file01
  98.  
    * @param file02
  99.  
    * @return
  100.  
    */
  101.  
    @ApiOperation("oss 分俩个file,多文件上传")
  102.  
    @PostMapping("filesUploadMore")
  103.  
    public ActionResult filesUploadMore(@RequestParam("file01") List<MultipartFile> file01, @RequestParam("file02") List<MultipartFile> file02) {
  104.  
    OssData ossData = new OssData();
  105.  
    Map<String, String> urls = new HashMap<>();
  106.  
    for (MultipartFile file : file01) {
  107.  
    try {
  108.  
    String url = ossUploadService.upload(file);
  109.  
    if (url != null) {
  110.  
    String fileName = file.getOriginalFilename();
  111.  
    url = fileHost + url;
  112.  
    urls.put(fileName, url);
  113.  
    } else {
  114.  
    ossData.setFileName(file.getOriginalFilename());
  115.  
    return ActionResult.fail(100, ossData, "上传失败");
  116.  
    }
  117.  
    } catch (Exception e) {
  118.  
    e.printStackTrace();
  119.  
    ossData.setFileName(file.getOriginalFilename());
  120.  
    return ActionResult.fail(100, ossData, "上传失败");
  121.  
    }
  122.  
    }
  123.  
     
  124.  
    for (MultipartFile file : file02) {
  125.  
    try {
  126.  
    String url = ossUploadService.upload(file);
  127.  
    if (url != null) {
  128.  
    String fileName = file.getOriginalFilename();
  129.  
    url = fileHost + url;
  130.  
    urls.put(fileName, url);
  131.  
    } else {
  132.  
    ossData.setFileName(file.getOriginalFilename());
  133.  
    return ActionResult.fail(100, ossData, "上传失败");
  134.  
    }
  135.  
    } catch (Exception e) {
  136.  
    e.printStackTrace();
  137.  
    ossData.setFileName(file.getOriginalFilename());
  138.  
    return ActionResult.fail(100, ossData, "上传失败");
  139.  
    }
  140.  
    }
  141.  
    return ActionResult.success(urls);
  142.  
    }
  143.  
    }
  144.  
     

工具类:

  1.  
    import com.fasterxml.jackson.annotation.JsonInclude;
  2.  
    import io.swagger.annotations.ApiModelProperty;
  3.  
    import jnpf.base.vo.PageListVO;
  4.  
    import jnpf.base.vo.PaginationVO;
  5.  
    import lombok.Data;
  6.  
     
  7.  
    import java.util.HashMap;
  8.  
    import java.util.List;
  9.  
    import java.util.Map;
  10.  
     
  11.  
    /**
  12.  
    * @author CYY
  13.  
    * @date 2022/4/15 16:43
  14.  
    */
  15.  
    @Data
  16.  
    @JsonInclude(JsonInclude.Include.NON_NULL)
  17.  
    public class ActionResult<T> {
  18.  
     
  19.  
    @ApiModelProperty("状态码")
  20.  
    private Integer code;
  21.  
     
  22.  
    @ApiModelProperty("返回信息")
  23.  
    private String msg;
  24.  
     
  25.  
    @ApiModelProperty("返回数据")
  26.  
    private T data;
  27.  
     
  28.  
    public static ActionResult success() {
  29.  
    ActionResult jsonData = new ActionResult();
  30.  
    jsonData.setCode(200);
  31.  
    jsonData.setMsg("Success");
  32.  
    return jsonData;
  33.  
    }
  34.  
     
  35.  
    public static ActionResult success(String msg) {
  36.  
    ActionResult jsonData = new ActionResult();
  37.  
    jsonData.setCode(200);
  38.  
    jsonData.setMsg(msg);
  39.  
    return jsonData;
  40.  
    }
  41.  
     
  42.  
    public static ActionResult success(Object rows, PageModel pageModel) {
  43.  
    ActionResult jsonData = new ActionResult();
  44.  
    Map<String, Object> map = new HashMap<>(16);
  45.  
    map.put("page", pageModel.getPage());
  46.  
    map.put("records", pageModel.getRecords());
  47.  
    map.put("rows", rows);
  48.  
    map.put("total", pageModel.getTotal());
  49.  
    jsonData.setData(map);
  50.  
    jsonData.setCode(200);
  51.  
    jsonData.setMsg("Success");
  52.  
    return jsonData;
  53.  
    }
  54.  
     
  55.  
    public static ActionResult success(Object object) {
  56.  
    ActionResult jsonData = new ActionResult();
  57.  
    jsonData.setData(object);
  58.  
    jsonData.setCode(200);
  59.  
    jsonData.setMsg("Success");
  60.  
    return jsonData;
  61.  
    }
  62.  
     
  63.  
    public static <T> ActionResult page(List<T> list, PaginationVO pagination) {
  64.  
    ActionResult jsonData = new ActionResult();
  65.  
    PageListVO<T> vo = new PageListVO<>();
  66.  
    vo.setList(list);
  67.  
    vo.setPagination(pagination);
  68.  
    jsonData.setData(vo);
  69.  
    jsonData.setCode(200);
  70.  
    jsonData.setMsg("Success");
  71.  
    return jsonData;
  72.  
    }
  73.  
     
  74.  
    public static ActionResult success(String msg, Object object) {
  75.  
    ActionResult jsonData = new ActionResult();
  76.  
    jsonData.setData(object);
  77.  
    jsonData.setCode(200);
  78.  
    jsonData.setMsg(msg);
  79.  
    return jsonData;
  80.  
    }
  81.  
     
  82.  
    public static ActionResult fail(Integer code, String message) {
  83.  
    ActionResult jsonData = new ActionResult();
  84.  
    jsonData.setCode(code);
  85.  
    jsonData.setMsg(message);
  86.  
    return jsonData;
  87.  
    }
  88.  
     
  89.  
    public static ActionResult fail(Integer code, Object object, String message) {
  90.  
    ActionResult jsonData = new ActionResult();
  91.  
    jsonData.setCode(code);
  92.  
    jsonData.setData(object);
  93.  
    jsonData.setMsg(message);
  94.  
    return jsonData;
  95.  
    }
  96.  
     
  97.  
    public static ActionResult fail(String msg, String data) {
  98.  
    ActionResult jsonData = new ActionResult();
  99.  
    jsonData.setMsg(msg);
  100.  
    jsonData.setData(data);
  101.  
    return jsonData;
  102.  
    }
  103.  
     
  104.  
    public static ActionResult fail(String msg) {
  105.  
    ActionResult jsonData = new ActionResult();
  106.  
    jsonData.setMsg(msg);
  107.  
    jsonData.setCode(400);
  108.  
    return jsonData;
  109.  
    }
  110.  
    }
  1.  
    import lombok.Data;
  2.  
     
  3.  
    import java.util.List;
  4.  
     
  5.  
    /**
  6.  
    * @author CYY
  7.  
    * @date 2022/4/15 16:43
  8.  
    */
  9.  
    @Data
  10.  
    public class PageListVO<T> {
  11.  
    private List<T> list;
  12.  
    PaginationVO pagination;
  13.  
     
  14.  
    }
  1.  
    import lombok.Data;
  2.  
     
  3.  
    /**
  4.  
    * @author CYY
  5.  
    * @date 2022/4/15 16:43
  6.  
    */
  7.  
    @Data
  8.  
    public class PaginationVO {
  9.  
    private Long currentPage;
  10.  
    private Long pageSize;
  11.  
    private Integer total;
  12.  
    }

转自:https://blog.csdn.net/HellocWood/article/details/124836732

posted @ 2023-07-27 11:13  甜菜波波  阅读(1785)  评论(0编辑  收藏  举报