阿里雲OSS上傳檔案工具類
阿新 • • 發佈:2019-02-12
/**
*
*
* 阿里雲OSS上傳檔案工具
*
* 支援普通檔案上傳,限制大小檔案上傳,限制大小圖片上傳
*
* @version1.0
*/
public class AliyunOssUtil {
private Logger logger = LoggerFactory.getLogger(AliyunOssUtil.class);
/**阿里雲API的內或外網域名*/
public static String ENDPOINT = "";
/**OSS簽名key*/
public static String ACCESS_KEY_ID = "";
/**OSS簽名金鑰*/
public static String ACCESS_KEY_SECRET = "";
/**儲存空間名稱*/
public static String BUCKETNAME = "";
private OSSClient ossClient = null;
Map<String, Object> resultMap = new HashMap<String, Object>();
/**
* 構造器,初始化引數。並例項化ossClient物件
*/
public AliyunOssUtil(){
try {
PropertiesUtil oss = new PropertiesUtil("OSSkey.properties");
Map<String, String> ossMap = oss.map;
ENDPOINT = ossMap.get("endpoint");
ACCESS_KEY_ID = ossMap.get("access_key_id");
ACCESS_KEY_SECRET = ossMap.get("access_key_secret");
BUCKETNAME = ossMap.get("bucketname");
logger.debug("初始化:應用資訊初始化--阿里雲API的內或外網域名:【{}】。 \n"
+ "訪問access_key:【{}】。 \n"
+ "訪問祕鑰access_key_secret:【{}】。 \n"
+ "oss儲存空間bucketName:【{}】",ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET,BUCKETNAME);
} catch (Exception e) {
e.printStackTrace();
}
// 初始化一個OSSClient
ossClient = new OSSClient(ENDPOINT,ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
/**
* 判斷bucket儲存空間是否已建立
* 若未建立,先建立一個Bucket
*/
public void ensureBucket() throws OSSException, ClientException {
try{
//判斷bucket是否存在
boolean exists = ossClient.doesBucketExist(AliyunOssUtil.BUCKETNAME);
if(!exists){
logger.error("bucket不存在,新建當前bucket:{}",AliyunOssUtil.BUCKETNAME);
ossClient.createBucket(AliyunOssUtil.BUCKETNAME);
}
}catch(ServiceException e){
logger.error(e.getErrorCode() + " " + e.getErrorMessage());
throw e;
}
}
/**
* 上傳檔案到OSS伺服器
* 如果同名檔案會覆蓋伺服器上的
*
* @param CommonsMultipartFile file 上傳檔案
* @param String dirName 檔案目錄名稱 (在oss中不存在目錄一說,只是用於形象的區分檔案種類)
* @param String fileName 檔名
* @return Map<String, Object> map
* stauts :true 上傳成功 。 false 上傳失敗
* msg :成功,返回檔案路徑。失敗,返回失敗資訊
*/
public Map<String, Object> uploadFileOSS(CommonsMultipartFile file,String dirName,String fileName) {
String ret = "";//上傳完成返回簽名
String uploadDir = "";//目錄名
String uploadPath = "";//儲存檔案路徑名稱
InputStream uploadInputStrem = null;
if(!"".equals(dirName) && dirName!=null){
uploadDir = dirName.substring(0, dirName.length()).replaceAll("\\\\","/")+"/";
}
try {
//判斷bucket是否存在
ensureBucket();
//獲取上傳檔案字尾名
String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
uploadPath = uploadDir + fileName + fileSuffix;
//建立上傳Object的Metadata。ObjectMetaData是使用者對該object的描述
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setContentEncoding("utf-8");
objectMetadata.setContentType(getcontentType(file,fileSuffix));//獲取檔案型別
objectMetadata.setContentDisposition("attachment;filename=" + fileName+fileSuffix);
uploadInputStrem = file.getInputStream(); //檔案輸入流
//上傳檔案
logger.debug("正在上傳檔案到OSS...");
PutObjectResult putResult = ossClient.putObject(AliyunOssUtil.BUCKETNAME, uploadPath, uploadInputStrem, objectMetadata);
logger.debug("上傳檔案完成...");
ret = putResult.getETag();
logger.debug("上傳後的檔案MD5數字唯一簽名:{}",ret);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (Exception e) {
logger.error(e.getMessage(), e);
resultMap.put("status", false);
resultMap.put("msg", "上傳失敗!");
return resultMap;
} finally {
try {
if (uploadInputStrem != null) {
uploadInputStrem.close();//關閉檔案流
}
if(ossClient != null){
this.destory();//銷燬oss物件
}
} catch (IOException e) {
e.printStackTrace();
}
}
if(!"".equals(ret) && ret!=null){
resultMap.put("status", true);
resultMap.put("msg", uploadPath);
return resultMap;
}else{
resultMap.put("status", false);
resultMap.put("msg", "上傳失敗!");
return resultMap;
}
}
/**
*
* 上傳檔案到OSS伺服器
* 如果同名檔案會覆蓋伺服器上已存在檔案
*
* @param CommonsMultipartFile file 上傳檔案
* @param String dirName 檔案目錄名稱 (在oss中不存在目錄一說,只是用於形象的區分檔案種類)
* @param String fileName 檔名
* @param int limitSize 上傳大小
* @return Map<String, Object> map
* stauts :true 上傳成功 。 false 上傳失敗
* msg :成功,返回檔案路徑。失敗,返回失敗資訊
*
*/
public Map<String, Object> UploadLimitSizeOSS(CommonsMultipartFile file,
String dirName, String fileName, int limitSize){
if (file == null) {
resultMap.put("status", false);
resultMap.put("msg", "未選擇檔案!");
this.destory();
return resultMap;
}
long limitSizeBytes = limitSize * 1024 * 1024;// 把單位M轉換為bytes
if (file.getSize() > limitSizeBytes) {
resultMap.put("status", false);
resultMap.put("msg", "您上傳的檔案超出限制大小" + limitSize + "M");
this.destory();
return resultMap;
}
return this.uploadFileOSS(file, dirName, fileName);
}
/**
*
* 上傳圖片到到OSS伺服器
* 如果同名檔案會覆蓋伺服器上已存在檔案
*
* @param CommonsMultipartFile file 上傳檔案
* @param String dirName 檔案目錄名稱 (在oss中不存在目錄一說,只是用於形象的區分檔案種類)
* @param String fileName 檔名
* @param int limitSize 上傳大小
* @return Map<String, Object> map
* stauts :true 上傳成功 。 false 上傳失敗
* msg :成功,返回檔案路徑。失敗,返回失敗資訊
*/
public Map<String, Object> ImgUploadLimitSizeOSS(CommonsMultipartFile file,
String dirName, String fileName, int limitSize){
if (file == null) {
resultMap.put("status", false);
resultMap.put("msg", "未選擇檔案!");
this.destory();
return resultMap;
}
if (!ImageUtil.fileIsImage(file)) {
resultMap.put("status", false);
resultMap.put("msg", "請選擇上傳圖片檔案!");
this.destory();
return resultMap;
}
long limitSizeBytes = limitSize * 1024 * 1024;// 把單位M轉換為bytes
if (file.getSize() > limitSizeBytes) {
resultMap.put("status", false);
resultMap.put("msg", "您上傳的檔案超出限制大小" + limitSize + "M");
this.destory();
return resultMap;
}
return this.uploadFileOSS(file, dirName, fileName);
}
/**
* 判斷OSS服務檔案上傳時檔案的contentType
*
* @param CommonsMultipartFile file 上傳檔案
* @param FilenameExtension 檔案字尾
* @return String
*/
public static String getcontentType(CommonsMultipartFile file,String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "image/bmp";
}
if (FilenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
}
if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
FilenameExtension.equalsIgnoreCase(".jpg") ||
FilenameExtension.equalsIgnoreCase(".png") ||
FilenameExtension.equalsIgnoreCase(".jpz") ) {
return "image/jpeg";
}
if (FilenameExtension.equalsIgnoreCase(".html") ||
FilenameExtension.equalsIgnoreCase(".htm") ||
FilenameExtension.equalsIgnoreCase(".hts")) {
return "text/html";
}
if (FilenameExtension.equalsIgnoreCase(".txt")) {
return "text/plain";
}
if (FilenameExtension.equalsIgnoreCase(".vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equalsIgnoreCase(".pptx") ||
FilenameExtension.equalsIgnoreCase(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equalsIgnoreCase(".docx") ||
FilenameExtension.equalsIgnoreCase(".doc")) {
return "application/msword";
}
if (FilenameExtension.equalsIgnoreCase(".xml")) {
return "text/xml";
}
if (FilenameExtension.equalsIgnoreCase(".xls")) {
return "application/vnd.ms-excel";
}
if (FilenameExtension.equalsIgnoreCase(".xlsx")) {
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
if (FilenameExtension.equalsIgnoreCase(".zip")) {
return "application/zip";
}
return file.getContentType();
}
/**
* 銷燬阿里雲OSS客戶端物件
*/
public void destory() {
ossClient.shutdown();
}
/**
* 獲取阿里雲遠端OSS指定檔案.並轉為輸出流
*
* @param String ossPrefix 訪問阿里雲oss檔案路徑 (http://ygzb.oss-cn-beijing.aliyuncs.com/)
* @param String fileUrl檔案儲存路徑 (如:upload/a.png)
* @param OutputStream oputstream 輸出流
* @throws IOException
*/
public static void downFile(String ossPrefix,String fileUrl,OutputStream oputstream) throws IOException{
InputStream iputstream = null;
try{
String ossFilePath = ossPrefix + fileUrl;//阿里雲網絡檔案地址
URL url = new URL(ossFilePath);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setDoInput(true);//設定是否要從 URL 連線讀取資料,預設為true
uc.connect();
iputstream = uc.getInputStream();
byte[] buffer = new byte[4*1024];
int byteRead = -1;
while((byteRead=(iputstream.read(buffer)))!= -1){
oputstream.write(buffer, 0, byteRead);
}
oputstream.flush();
} catch (Exception e) {
System.out.println("讀取失敗!");
e.printStackTrace();
} finally{
if(iputstream != null){
iputstream.close();
}
}
}
}