上个项目中使用到了京东云的OSS服务,这里记录一下,方便今后使用!
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.136</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.1</version>
</dependency>
根据需求选择(根据个人情况而定,本人在这里测试使用,也不商用,所在就公有读写了)
空间名称就是# oss的存储空间
jd.oss.bucketName=xxxxx
/**
* 上传文件到京东云OSS
* @param uploadFile
*/
@PostMapping("/file/upload")
public String upload(@RequestParam("file") MultipartFile uploadFile){
String filePath = "";
try {
filePath = getFilePath(uploadFile.getOriginalFilename());
// 将MultipartFile对象转换为File
File file = File.createTempFile("tmp", null);
uploadFile.transferTo(file);
initS3().putObject(bucketName, filePath, file);
} catch (Exception e) {
e.printStackTrace();
}
return filePath;
}
/**
* 从OSS上下载文件
*/
@GetMapping("/file/download")
public void downLoad(@RequestParam(value = "fileName", required=true) String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception{
response.reset();
// OSS上的服务有个桶,所以切割一下,拿到正确的文件名
String name = fileName.split("/")[1];
// 设置response的Header 获取浏览器名(IE/Chome/firefox)
String userAgent = request.getHeader("User-Agent").toLowerCase();
// 火狐
if (userAgent.contains("firefox")) {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("UTF-8"), "ISO8859-1"));
// IE浏览器
} else if (StringUtils.contains(userAgent, "msie")
|| StringUtils.contains(userAgent, "trident")
|| StringUtils.contains(userAgent,"edge")
|| userAgent.contains("like gecko")) {
name = URLEncoder.encode(name, "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + name);
// 谷歌
}else if (userAgent.contains("chrome")) {
response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("UTF-8"), "ISO8859-1"));
} else {
URLEncoder.encode(name, "UTF-8");
}
response.setContentType("application/octet-stream");
download(response.getOutputStream(), fileName);
}
/**
* 下载文件
* @param outputStream
* @param fileName
* @throws Exception
*/
private void download(ServletOutputStream outputStream, String fileName) throws Exception {
// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
S3Object s3Object = initS3().getObject(bucketName, fileName);
// 读取文件内容。
BufferedInputStream in = new BufferedInputStream(s3Object.getObjectContent());
BufferedOutputStream out = new BufferedOutputStream(outputStream);
byte[] buffer = new byte[1024];
int lenght = 0;
while ((lenght = in.read(buffer)) > 0) {
out.write(buffer, 0, lenght);
}
if (out != null) {
out.flush();
out.close();
}
if (in != null) {
in.close();
}
}
/**
* 删除OSS上的文件
*/
@GetMapping("/file/delete")
public void delete(@RequestParam("fileName") String fileName){
initS3().deleteObject(bucketName, fileName);
}
此路径就是fileName.删除操作,下载都需要此fileName
/**
* 文件保存的路径
*
* @param sourceFileName
* @return
*/
private String getFilePath(String sourceFileName) {
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(sourceFileName, type)) {
return "image/" + getTime() + "." + StringUtils.substringAfterLast(sourceFileName, ".");
}
}
return "file/" + getTime() + "." + StringUtils.substringAfterLast(sourceFileName, ".");
}
/**
* 时间转换
* @return
*/
public String getTime(){
SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmss");
String time = dateformat.format(new Date());
return time;
}
private AmazonS3 initS3() {
System.setProperty(SDKGlobalConfiguration.ENABLE_S3_SIGV4_SYSTEM_PROPERTY, "true");
ClientConfiguration config = new ClientConfiguration();
AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration(endpoint, "cn-north-1");
AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, accessKeySecret);
AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);
AmazonS3 s3 = AmazonS3Client.builder()
.withEndpointConfiguration(endpointConfig)
.withClientConfiguration(config)
.withCredentials(awsCredentialsProvider)
.disableChunkedEncoding()
.withPathStyleAccessEnabled(true)
.build();
return s3;
}
这里使用postman测试,post请求,key与Controller里的@RequestParam(“file”)
对应,选择file格式
发送请求会返回一个fileName的路径,上传OK!可以在oss上看到
get请求,拼接的fileName就是刚才上传成功返回的(本人亲自炸的花生米,确实好吃.哈哈哈…)
还可以拼接外链访问,可以自行研究下
没有做返回值,所以执行删除了看不出来.只能再执行次下载操作才可以看到效果
其实已经删除了0.0
控制台也给出提示了,不存在了,所以下载不了了
其实引入一个新技术,就是几个流程:
1.引入pom/gradle
2.配置properties/yml
3.看情况写config
4.写一些xml
5.调用api
京东云OSS只用到了1,2,5 其实初始化那个可以写入到config里,注入方式来引入
=======================
=============