集成aliyun oss

结构如下:

pom.xml

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- aliyun bigen -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>${aliyun.oss.version}</version>
</dependency> <dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- aliyun end -->
<!-- lombok bigen -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- lombok end -->

application.yml

aliyun:
file:
endpoint: http://oss-cn-hangzhou.aliyuncs.com
accessKeyId: *******************
accessKeySecret: *******************
bucketName: tzqimg
folder : test
webUrl: https://tzqimg.oss-cn-hangzhou.aliyuncs.com spring:
servlet:
multipart:
max-file-size: 1MB
max-request-size: 1MB
package com.aliyun.we;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component; @Data
@Component
@Configuration
public class ConstantConfig {
@Value("${aliyun.file.endpoint}")
private String endpoint;
@Value("${aliyun.file.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.file.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.file.folder}")
private String folder;
@Value("${aliyun.file.bucketName}")
private String bucketName;
@Value("${aliyun.file.webUrl}")
private String webUrl; }
package com.aliyun.we;

import lombok.Data;

import java.io.Serializable;

/**
* @description: 文件上传信息存储类
* @author: tzq
* @create 2019-08-06
*/
@Data
public class FileDTO implements Serializable { /**
* 文件大小
*/
private Long fileSize;
/**
* 文件的绝对路径
*/
private String fileAPUrl; /**
* 文件的web访问地址
*/
private String webUrl; /**
* 文件后缀
*/
private String fileSuffix;
/**
* 存储的bucket
*/
private String fileBucket; /**
* 原文件名
*/
private String oldFileName;
/**
* 存储的文件夹
*/
private String folder; public FileDTO() {
} public FileDTO(Long fileSize, String fileAPUrl, String webUrl, String fileSuffix, String fileBucket, String oldFileName, String folder) {
this.fileSize = fileSize;
this.fileAPUrl = fileAPUrl;
this.webUrl = webUrl;
this.fileSuffix = fileSuffix;
this.fileBucket = fileBucket;
this.oldFileName = oldFileName;
this.folder = folder;
}
}
package com.aliyun.we;

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 org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID; @Component
public class AliyunOSSUtil {
@Autowired
private ConstantConfig constantConfig;
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class); /** 上传文件*/
public FileDTO upLoad(File file){
logger.info("------OSS文件上传开始--------"+file.getName());
String endpoint=constantConfig.getEndpoint();
System.out.println("获取到的Point为:"+endpoint);
String accessKeyId=constantConfig.getAccessKeyId();
String accessKeySecret=constantConfig.getAccessKeySecret();
String bucketName=constantConfig.getBucketName();
String fileHost=constantConfig.getFolder();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
String dateStr=format.format(new Date());
String uuid = UUID.randomUUID().toString().replace("-", "");
String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
// 判断文件
if(file==null){
return null;
}
OSSClient client=new OSSClient(endpoint, accessKeyId, accessKeySecret);
try {
// 判断容器是否存在,不存在就创建
if (!client.doesBucketExist(bucketName)) {
client.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
client.createBucket(createBucketRequest);
}
// 设置文件路径和名称
String fileUrl = fileHost + "/" + (dateStr + "/" + uuid ) + "-" + file.getName();
// 设置权限(公开读)
client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
// 上传文件
PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file)); if (result != null) {
System.out.println(result);
logger.info("------OSS文件上传成功------" + fileUrl);
return new FileDTO(
file.length(),//文件大小
fileUrl,//文件的绝对路径
constantConfig.getWebUrl() +"/"+ fileUrl,//文件的web访问地址
suffix,//文件后缀
"",//存储的bucket
bucketName,//原文件名
fileHost//存储的文件夹
); }
}catch (OSSException oe){
logger.error(oe.getMessage());
}catch (ClientException ce){
logger.error(ce.getErrorMessage());
}finally{
if(client!=null){
client.shutdown();
}
}
return null;
}
}
package com.aliyun.we;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import java.io.File;
import java.io.FileOutputStream; @RestController
public class UpLoadController { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired
private AliyunOSSUtil aliyunOSSUtil; /** 文件上传*/
@RequestMapping(value = "/uploadFile")
public FileDTO uploadBlog(@RequestParam("file") MultipartFile file) {
logger.info("文件上传");
String filename = file.getOriginalFilename();
System.out.println(filename); try {
// 判断文件
if (file!=null) {
if (!"".equals(filename.trim())) {
File newFile = new File(filename);
FileOutputStream os = new FileOutputStream(newFile);
os.write(file.getBytes());
os.close();
file.transferTo(newFile);
// 上传到OSS
return aliyunOSSUtil.upLoad(newFile);
} }
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}

postman 返回

{
"fileSize": 190280,
"fileAPUrl": "test/2019-08-06/5ea96123bc3f4fa0a30560ae6aa2f285-WX20190806-151311@2x.png",
"webUrl": "https://tzqimg.oss-cn-hangzhou.aliyuncs.com/test/2019-08-06/5ea96123bc3f4fa0a30560ae6aa2f285-WX20190806-151311@2x.png",
"fileSuffix": "png",
"fileBucket": "",
"oldFileName": "tzqimg",
"folder": "test"
}

springboot 集成oss的更多相关文章

  1. springboot集成oss阿里云存储

    一.注册阿里云 二.购买OSS 三.创建桶 设定权限,其它默认即可 四.创建目录 点击桶名,进入创建目录即可. 五.开发文档 引入依赖: <dependency> <groupId& ...

  2. 【springBoot】springBoot集成redis的key,value序列化的相关问题

    使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...

  3. SpringBoot集成security

    本文就SpringBoot集成Security的使用步骤做出解释说明.

  4. springboot集成Actuator

    Actuator监控端点,主要用来监控与管理. 原生端点主要分为三大类:应用配置类.度量指标类.操作控制类. 应用配置类:获取应用程序中加载的配置.环境变量.自动化配置报告等与SpringBoot应用 ...

  5. SpringBoot集成Shiro并用MongoDB做Session存储

    之前项目鉴权一直使用的Shiro,那是在Spring MVC里面使用的比较多,而且都是用XML来配置,用Shiro来做权限控制相对比较简单而且成熟,而且我一直都把Shiro的session放在mong ...

  6. SpringBoot集成redis的key,value序列化的相关问题

    使用的是maven工程 springBoot集成redis默认使用的是注解,在官方文档中只需要2步; 1.在pom文件中引入即可 <dependency> <groupId>o ...

  7. springboot集成mybatis(二)

    上篇文章<springboot集成mybatis(一)>介绍了SpringBoot集成MyBatis注解版.本文还是使用上篇中的案例,咱们换个姿势来一遍^_^ 二.MyBatis配置版(X ...

  8. springboot集成mybatis(一)

    MyBatis简介 MyBatis本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation迁移到了google code,并且改名为MyB ...

  9. springboot集成redis(mybatis、分布式session)

    安装Redis请参考:<CentOS快速安装Redis> 一.springboot集成redis并实现DB与缓存同步 1.添加redis及数据库相关依赖(pom.xml) <depe ...

随机推荐

  1. MySQL技术内幕 InnoDB存储引擎 之 InnoDB体系架构

    后台线程 1.Master Thread 2.IO Thread 3.Purge Thread 4.Page Cleaner Thread  内存 重做日志在以下三种情况下将重做日志缓存中的内容刷新到 ...

  2. mac 外接显示屏的坑

    概述 工作中使用 Mac 外接显示屏,有时会出现闪屏然后黑屏的现象,之前都没有找到原因,今天终于找到了,记录下来,供以后参考,相信对其他人也有用. 参考资料: Macbook外接显示器设置教程 问题 ...

  3. 阶段2 JavaWeb+黑马旅游网_15-Maven基础_第4节 maven生命周期和概念模型图_09maven概念模型图

    项目自身的信息 项目运行所依赖的扎包 运行环境信息:tomcat啊,JDK啊这些都属于运行环境 一个jar包的坐标由三个最基本的信息组成. 第一部分就是依赖管理. 第二个部分

  4. 中国MOOC_零基础学Java语言_第2周 判断

    浮点数判断大小 public class Main { public static void main(String[] args) { double a = 1.0; double b = 0.1 ...

  5. python调用java代码 java虚拟机(jvm)

    1.新建com文件夹,在里面新建 fibnq.java package com; public class fibnq { public fibnq(){} public int fb(int n){ ...

  6. [JS] 鼠标点击文本框清空默认值,离开文本框恢复默认值

    在使用文本框的时候,若设定了初始值,选择文本框进行输入的时候要将本来的内容进行删除,会显得非常麻烦 可以在文本框属性定义触发onfocus和onblur两个事件时对应的js功能 下面以asp.net代 ...

  7. git自动上传脚本及基本代码

    git_auto.bat git add . git add -A git add -u git commit -m "text" git pull --rebase origin ...

  8. MySQL服务意外停止

    先说一下,发现MySQL服务停了,启动就又好了,但是好奇服务意外停止的原因,所以看了一下MySQL的错误日志. 但是到底是哪个错误导致MySQL服务意外终止,还没有定论,故有了此篇文章,还望知道原因的 ...

  9. 为什么你的javascript学了这么久,水平还是烂成了渣?

    今年我给公司面试时,面试了百来个人,水平我就呵呵了,还觉得自己学了很久很厉害了,其实呢,渣的很呀,这篇文章送给想学好javascript找份工作的同学们. 首先要说明的是,咱现在不是高手,最多还是一个 ...

  10. Java 5种单例模式

    /*单例模式: 指某个类中只能存在一个对象实例,并且该类中只提供一个取得其对象实例的方法 优点:减少系统性能开销 应用场景:网站的计数器,任务管理器,回收站等*/   //单例模式1 -- 静态内部类 ...