aliyun-sdk-oss-2.2.1.jar
hamcrest-core-1.1.jar
jdom-1.1.jar
commons-codec-1.9.jar
httpclient-4.4.1.jar
commons-logging-1.2.jar
httpcore-4.4.1.jar
log4j-1.2.15.jarhtml
public class AliyunOSSClientUtil {
//log日誌
private static Logger logger = Logger.getLogger(AliyunOSSClientUtil.class);
//阿里雲API的內或外網域名
private static String ENDPOINT;
//阿里雲API的密鑰Access Key ID
private static String ACCESS_KEY_ID;
//阿里雲API的密鑰Access Key Secret
private static String ACCESS_KEY_SECRET;
//阿里雲API的bucket名稱
private static String BACKET_NAME;
//阿里雲API的文件夾名稱
private static String FOLDER;
//初始化屬性
static {
ENDPOINT = OSSClientContstants.ENDPOINT;
ACCESS_KEY_ID = OSSClientContstants.ACCESS_KEY_ID;
ACCESS_KEY_SECRET = OSSClientContstants.ACCESS_KEY_SECRET;
BACKET_NAME = OSSClientContstants.BUCKET_NAME;
FOLDER = OSSClientContstants.FOLDER;
}
/**
* 獲取阿里雲OSS客戶端對象
*
* @return ossClient
*/
public static OSSClient getOSSClient() {
return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
}
/**
* 建立存儲空間
*
* @param ossClient OSS鏈接
* @param bucketName 存儲空間
* @return
*/
public static String createBucketName(OSSClient ossClient, String bucketName) {
//存儲空間
final String bucketNames = bucketName;
if (!ossClient.doesBucketExist(bucketName)) {
//建立存儲空間
Bucket bucket = ossClient.createBucket(bucketName);
logger.info("建立存儲空間成功");
return bucket.getName();
}
return bucketNames;
}
/**
* 刪除存儲空間buckName
*
* @param ossClient oss對象
* @param bucketName 存儲空間
*/
public static void deleteBucket(OSSClient ossClient, String bucketName) {
ossClient.deleteBucket(bucketName);
logger.info("刪除" + bucketName + "Bucket成功");
}
/**
* 建立模擬文件夾
*
* @param ossClient oss鏈接
* @param bucketName 存儲空間
* @param folder 模擬文件夾名如"qj_nanjing/"
* @return 文件夾名
*/
public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
//文件夾名
final String keySuffixWithSlash = folder;
//判斷文件夾是否存在,不存在則建立
if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
//建立文件夾
ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
logger.info("建立文件夾成功");
//獲得文件夾名
OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
String fileDir = object.getKey();
return fileDir;
}
return keySuffixWithSlash;
}
/**
* 根據key刪除OSS服務器上的文件
*
* @param ossClient oss鏈接
* @param bucketName 存儲空間
* @param folder 模擬文件夾名 如"qj_nanjing/"
* @param key Bucket下的文件的路徑名+文件名 如:"upload/cake.jpg"
*/
public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key) {
ossClient.deleteObject(bucketName, folder + key);
logger.info("刪除" + bucketName + "下的文件" + folder + key + "成功");
}
/**
* 上傳圖片至OSS
*
* @param ossClient oss鏈接
* @param file 上傳文件(文件全路徑如:D:\\image\\cake.jpg)
* @param bucketName 存儲空間
* @param folder 模擬文件夾名 如"qj_nanjing/"
* @return String 返回的惟一MD5數字簽名
*/
public static String uploadObject2OSS(OSSClient ossClient, MultipartFile file, String bucketName, String folder) {
String resultStr = null;
String uploadName=null;
try {
//以輸入流的形式上傳文件
InputStream is = file.getInputStream();
//文件名
String fileName = is.getClass().getName();
//文件大小
Long fileSize = file.getSize();
//建立上傳Object的Metadata
ObjectMetadata metadata = new ObjectMetadata();
//上傳的文件的長度
metadata.setContentLength(is.available());
//指定該Object被下載時的網頁的緩存行爲
metadata.setCacheControl("no-cache");
//指定該Object下設置Header
metadata.setHeader("Pragma", "no-cache");
//指定該Object被下載時的內容編碼格式
metadata.setContentEncoding("utf-8");
//文件的MIME,定義文件的類型及網頁編碼,決定瀏覽器將以什麼形式、什麼編碼讀取文件。若是用戶沒有指定則根據Key或文件名的擴展名生成,
//若是沒有擴展名則填默認值application/octet-stream
metadata.setContentType(getContentType(fileName));
//指定該Object被下載時的名稱(指示MINME用戶代理如何顯示附加的文件,打開或下載,及文件名稱)
metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
//上傳文件 (上傳文件流的形式)
//上傳的文件名稱
uploadName= UUID.randomUUID().toString();
PutObjectResult putResult = ossClient.putObject(bucketName, folder + uploadName, is, metadata);
//解析結果
resultStr = putResult.getETag();
} catch (Exception e) {
e.printStackTrace();
logger.error("上傳阿里雲OSS服務器異常." + e.getMessage(), e);
}
return folder+uploadName;
}
/**
* 經過文件名判斷並獲取OSS服務文件上傳時文件的contentType
*
* @param fileName 文件名
* @return 文件的contentType
*/
public static String getContentType(String fileName) {
//文件的後綴名
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
if (".bmp".equalsIgnoreCase(fileExtension)) {
return "image/bmp";
}
if (".gif".equalsIgnoreCase(fileExtension)) {
return "image/gif";
}
if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension)) {
return "image/jpeg";
}
if (".html".equalsIgnoreCase(fileExtension)) {
return "text/html";
}
if (".txt".equalsIgnoreCase(fileExtension)) {
return "text/plain";
}
if (".vsd".equalsIgnoreCase(fileExtension)) {
return "application/vnd.visio";
}
if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
return "application/vnd.ms-powerpoint";
}
if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
return "application/msword";
}
if (".xml".equalsIgnoreCase(fileExtension)) {
return "text/xml";
}
//默認返回類型
return "image/jpeg";
}
寫一個form表單選擇上傳圖片
<form action="/a/App/LikeApp/fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
返回的url由幾個參數拼接
@ResponseBody
@RequestMapping(value ="fileUpload",method = RequestMethod.POST)
public ObjectStatus FileUpload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
String md5key = AliyunOSSClientUtil.uploadObject2OSS(ossClient, file, BUCKET_NAME, FOLDER);
String s = "https://" + BUCKET_NAME + "." + ENDPOINT + "/" + md5key;
return new ObjectStatus("200","success",s);
}