阿里雲oss多文件批量獲取打成zip包上傳下載詳解-Java版


1:pom.xml中添加maven依賴:

<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>

 

2:下載主要方法代碼:

@RequestMapping("/api/downlownd")
public String getOssFile(HttpServletRequest request, HttpServletResponse response){

// endpoint以杭州為例,其它region請按實際情況填寫,1改為自己的
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 雲賬號AccessKey有所有API訪問權限,建議遵循阿里雲安全最佳實踐,創建並使用RAM子賬號進行API訪問或日常運維,請登錄 https://ram.console.aliyun.com 創建
String accessKeyId = "2改為自己的";
String accessKeySecret = "3改為自己的";
String bucketName = "4改為自己的";
//要下載的文件名(Object Name)字符串,中間用‘,’間隔。文件名從bucket目錄開始.5改為自己的

//todo 這個key 是上傳時候的key,如下有上傳案例的講解

String key = "focus/item/P8c5z8BKWY1533108107411.png,focus/item/fJ4WmmbM5w1533108018272.png";
try {
// 初始化
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);;
//6改為自己的名稱
String fileName = "test.zip";
// 創建臨時文件
File zipFile = File.createTempFile("test", ".zip");
FileOutputStream f = new FileOutputStream(zipFile);
/**
* 作用是為任何OutputStream產生校驗和
* 第一個參數是制定產生校驗和的輸出流,第二個參數是指定Checksum的類型 (Adler32(較快)和CRC32兩種)
*/
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
// 用於將數據壓縮成Zip文件格式
ZipOutputStream zos = new ZipOutputStream(csum);

String[] keylist = key.split(",");
for (String ossfile : keylist) {
// 獲取Object,返回結果為OSSObject對象
OSSObject ossObject = ossClient.getObject(bucketName, ossfile);
// 讀去Object內容 返回
InputStream inputStream = ossObject.getObjectContent();
// 對於每一個要被存放到壓縮包的文件,都必須調用ZipOutputStream對象的putNextEntry()方法,確保壓縮包里面文件不同名

zos.putNextEntry(new ZipEntry(ossfile.split("/")[2]));
int bytesRead = 0;
// 向壓縮文件中輸出數據
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"); //IE下載文件名空格變+號問題
} 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();
// 刪除臨時文件
zipFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

 

3:上傳案例

 /**
*
* @MethodName: putObject
* @Description: 上傳文件
* @param fileType 文件后綴,比如 png,...
* @param fileName
* @return String
*/
private String putObject(InputStream input,String fileType,String fileName){
String url = null;
//默認null
OSSClient ossClient = null;
try {
ossClient = new OSSClient(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
// InputStream input = new FileInputStream(file);
ObjectMetadata meta = new ObjectMetadata();
// 創建上傳Object的Metadata
meta.setContentType(contentType(fileType));
// 設置上傳內容類型
meta.setCacheControl("no-cache");

boolean exists = ossClient.doesBucketExist(config.getBucketName());
if (!exists) {
ossClient.createBucket(config.getBucketName());
}
// 被下載時網頁的緩存行為
PutObjectRequest request = new PutObjectRequest(config.getBucketName(), fileName,input,meta);
//創建上傳請求
// ossClient.putObject(request);
StringBuilder sb = new StringBuilder(PIC_LOCATION);
sb.append(fileName);
       //todo 如下這個key就是 下載時的那個
System.out.println("key: "+sb.toString());
ossClient.putObject(config.getBucketName(),sb.toString(),input);
url = config.getEndpoint().replaceFirst("http://","http://"+config.getBucketName()+".")+"/"+fileName;
//上傳成功再返回的文件路徑
} catch (OSSException oe) {
oe.printStackTrace();
return null;
} catch (ClientException ce) {
ce.printStackTrace();
return null;
} finally {
ossClient.shutdown();
}
return url;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM