文件上传oss
api查看
https://help.aliyun.com/document_detail/
jar包引入
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
其核心配置
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-beijing.aliyuncs.com";
// 使用刚刚创建的accessKeyId和accessKeySecret
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
// 创建OSSClient实例。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//todo
// 关闭OSSClient。
ossClient.shutdown();
上传文件
配置文件ossConfig
package com.meeno.chemical.common.oss.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
/**
* Oss配置类
* @author LGL
* @date 2020/9/15 19:29
*/
@Configuration
public class OssConfig {
/**
* 地区
*/
public static String region;
/**
* 访问密钥Id
*/
public static String accessKeyId;
/**
* 账号密匙
*/
public static String accessKeySecret;
/**
* 名称
*/
public static String bucket;
@Value("${oss.region}")
public void setRegion(String region) {
OssConfig.region = region;
}
@Value("${oss.accessKeyId}")
public void setAccessKeyId(String accessKeyId) {
OssConfig.accessKeyId = accessKeyId;
}
@Value("${oss.accessKeySecret}")
public void setAccessKeySecret(String accessKeySecret) {
OssConfig.accessKeySecret = accessKeySecret;
}
@Value("${oss.bucket}")
public void setBucket(String bucket) {
OssConfig.bucket = bucket;
}
}
其在yaml中的配置
oss:
region: oss-cn-shanghai
accessKeyId: **********
accessKeySecret: *************
bucket: *******
通过流的方式上传文件,返回可以预览图片的地址
/**
* 通过流的方式上传文件,返回可以预览图片的地址
* @param file
* @return
*/
public static String uploadFilePreviewImageByStream(MultipartFile file){
String bucketName = OssConfig.bucket;
String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
String accessKeyId = OssConfig.accessKeyId;
String accessKeySecret = OssConfig.accessKeySecret;
// 获取文件的后缀名
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//生成上传文件名
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
// 生成存储路径
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String objectName = sdf.format(new Date()) + "/" + finalFileName;
//生成新的文件
File files;
try (InputStream ins = file.getInputStream()) {
files = new File(file.getOriginalFilename());
inputStreamToFile(ins, files);
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, objectName, files);
// 设置URL过期时间为1小时。
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
log.info(url.toString());
ossClient.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
String url = "http://" + bucketName + "." + OssConfig.region + ".aliyuncs.com" + "/" + objectName;
return url;
}
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();
}
}
通过上传文件位置的方式上传文件,返回可以预览文件的地址
/**
* 上传文件,返回可以预览文件的地址
* @param fullPath "/Users/dalaoyang/Desktop/aliyun.jpeg"
* @return
*/
public static String uploadFilePreviewImageByAddress(String fullPath) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
String accessKeyId = OssConfig.accessKeyId;
String accessKeySecret = OssConfig.accessKeySecret;
String fileName = fullPath;
String bucketName = OssConfig.bucket;
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 生成上传文件名
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
String objectName = sdf.format(new Date()) + "/" + finalFileName;
File file = new File(fileName);
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, objectName, file);
// 设置URL过期时间为1小时。
// Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
// URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
ossClient.shutdown();
String url = "http://" + bucketName + "." + OssConfig.region + ".aliyuncs.com" + "/" + objectName;
return url;
}
通过上传文件位置的方式上传文件,返回可以直接下载文件的地址
/**
* 上传文件,返回可以直接下载文件的地址
* @param fullPath" /Users/dalaoyang/Desktop/aliyun.jpeg"
* @return
*/
public static String uploadFileDownloadPictures(String fullPath) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String bucketName = OssConfig.bucket;
String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
String accessKeyId = OssConfig.accessKeyId;
String accessKeySecret = OssConfig.accessKeySecret;
String fileName = fullPath;
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 生成上传文件名
String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
String objectName = sdf.format(new Date()) + "/" + finalFileName;
File file = new File(fileName);
ObjectMetadata meta = new ObjectMetadata();
meta.setContentDisposition("attachment;");
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, objectName, file, meta);
// 设置URL过期时间为1小时。
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
ossClient.shutdown();
return url.toString();
}
下载多个 oss文件并压缩 zip
/**
* 下载多个 oss文件并压缩 zip
* @param request
* @param response
* @param keys 文件地址
* @return
*/
public static String getOssFile(HttpServletRequest request, HttpServletResponse response, List<String> keys) {
String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
String accessKeyId = OssConfig.accessKeyId;
String accessKeySecret = OssConfig.accessKeySecret;
String bucketName = OssConfig.bucket;
try {
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
String fileName = "数据报告.zip";
File zipFile = File.createTempFile("test", ".zip");
FileOutputStream f = new FileOutputStream(zipFile);
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
for (String ossfile : keys) {
//简单处理文件地址
ossfile = ossfile.substring(endpoint.length() + 7, ossfile.lastIndexOf("?"));
//处理文件地址乱码问题
ossfile = URLDecoder.decode(ossfile, "UTF-8");
OSSObject ossobject = ossClient.getObject(bucketName, ossfile);
InputStream inputStream = ossobject.getObjectContent();
//处理命名问题
zos.putNextEntry(new ZipEntry(ossfile.split("/")[1]));
int bytesRead;
while ((bytesRead = inputStream.read()) != -1) {
zos.write(bytesRead);
}
inputStream.close();
zos.closeEntry();
}
zos.close();
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "utf-8");
fileName = fileName.replace("+", "%20");
} else {
fileName = new String(fileName.getBytes(), "ISO8859-1");
}
response.reset();
response.setContentType("text/plain");
response.setContentType("application/octet-stream; charset=utf-8");
response.setHeader("Location", fileName);
response.setHeader("Cache-Control", "max-age=0");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
FileInputStream fis = new FileInputStream(zipFile);
BufferedInputStream buff = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
byte[] car = new byte[1024];
int l = 0;
while (l < zipFile.length()) {
int j = buff.read(car, 0, 1024);
l += j;
out.write(car, 0, j);
}
fis.close();
buff.close();
out.close();
ossClient.shutdown();
System.out.println(zipFile.getName());
zipFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}