Java上传文件到阿里云的对象存储OSS
首先这操作OSS的文档在
1.导入maven依赖
<dependencies> <!-- 阿里云oss依赖 --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> </dependency> <!-- 日期工具栏依赖,用于后面生成日期的 --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> </dependency> </dependencies>
2. 在配置文件中配置OSS的相应内容:
#服务端口 server.port=8002 #服务名 spring.application.name=service-oss #环境设置:dev、test、prod spring.profiles.active=dev #阿里云 OSS #不同的服务器,地址不同 aliyun.oss.file.endpoint=自己的地域结点 aliyun.oss.file.keyid=自己的id aliyun.oss.file.keysecret=自己的密码 #bucket可以在控制台创建,也可以使用java代码创建 aliyun.oss.file.bucketname=自己创建的bucket的名字
3. 新建一个工具类用来读取配置文件中的数据
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ConstantPropertiesUtils implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyId;
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketname;
public static String END_POINT;
public static String KEY_ID;
public static String KEY_SECRET;
public static String BUCKETNAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT=endpoint;
KEY_ID=keyId;
KEY_SECRET=keySecret;
BUCKETNAME=bucketname;
}
}
4.业务逻辑代码
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@Service
public class OssServiceImpl implements OssService {
@Override//参数中的文件上传到OSS中,
public String uploadFileAvatar(MultipartFile file) {
// Endpoint以北京为例,其它Region请按实际情况填写。
String endpoint = ConstantPropertiesUtils.END_POINT;
String accessKeyId = ConstantPropertiesUtils.KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
String bucketName = ConstantPropertiesUtils.BUCKETNAME;
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().
build(endpoint, accessKeyId, accessKeySecret);//地域结点,id,密码
//第2个参数:文件的名称
String filename = file.getOriginalFilename();
//让每个文件名称都不一样并且通过日期进行分组存储,否则后面的文件会覆盖掉前面的文件
String uuid = UUID.randomUUID().toString().replaceAll("-","");
filename = uuid + filename;
String datePath = new DateTime().toString("yyyy/MM/dd");
filename=datePath+"/"+filename;
//第3个参数:获得文件的流
InputStream inputStream = file.getInputStream();
ossClient.putObject(bucketName,filename,inputStream); //上传文件
ossClient.shutdown(); //关闭该实例
//把上传到阿里云的路径手动拼接出来,然后返回
String url="https://"+bucketName+"."+endpoint+"/"+filename;
return url;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
上一篇:
IDEA上Java项目控制台中文乱码
