阿里的oss工具類
package co.chexiao.lucky.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import co.chexiao.lucky.util.HttpUtil;
public class OSSClientUtil {
private static Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
private static String CONTENT_TYPE_IMAGE = "image/jpeg";
private static String CONTENT_TYPE_TXT = "text/xml";
private static String CONTENT_TYPE_PDF = "application/pdf";
private static String CONTENT_TYPE_EXECL = "application/vnd.ms-excel";
private static OSSClient ossClient;
private static OSSClient ossClientUrl;
private static String bucketName = co.chexiao.lucky.util.PropertiesUtil.getValueByKey("oss.bucketName");
static {
ossClient = new OSSClient(PropertiesUtil.getValueByKey("oss.endpoint"),
PropertiesUtil.getValueByKey("oss.accessKeyId"),
PropertiesUtil.getValueByKey("oss.accessKeySecret"));
ossClientUrl = new OSSClient(PropertiesUtil.getValueByKey("oss.endpoint.url"),
PropertiesUtil.getValueByKey("oss.accessKeyId"),
PropertiesUtil.getValueByKey("oss.accessKeySecret"));
}
private static OSSClient getOssClient() {
return ossClient;
}
private static String getBucketName() {
return bucketName;
}
private static void setOssClient(OSSClient ossClient) {
OSSClientUtil.ossClient = ossClient;
}
private static void setBucketName(String bucketName) {
OSSClientUtil.bucketName = bucketName;
}
public static OSSClient getOssClientUrl() {
return ossClientUrl;
}
public static void setOssClientUrl(OSSClient ossClientUrl) {
OSSClientUtil.ossClientUrl = ossClientUrl;
}
/**
* 上傳文件至阿里云
* @param imgBase64Content:待上傳圖片Base64字符串內(nèi)容
* @param key: 阿里云文件名
* @return
* @throws IOException
*/
public static String uploadBase64Img2OSS(String imgBase64Content, String key) {
InputStream in = null;
try {
if (imgBase64Content != null) {
BASE64Decoder decoder = new BASE64Decoder();
imgBase64Content = imgBase64Content.replace("data:image/jpeg;base64,", "");
imgBase64Content = imgBase64Content.replace(" ", "+").replace("\r\n", "");
byte[] content = decoder.decodeBuffer(imgBase64Content);
for (int i = 0; i < content.length; ++i) {
if (content[i] < 0) {// 調(diào)整異常數(shù)據(jù)
content[i] += 256;
}
}
in = new ByteArrayInputStream(content);
return uploadFile2OSS(key, in, CONTENT_TYPE_IMAGE);
} else {
return null;
}
} catch (Exception e) {
logger.error("uploadImg2OSS failed:" + e.getMessage());
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
}
}
}
}
/**
* 上傳文件至阿里云
* @param pdfBase64Content:待上傳圖片Base64字符串內(nèi)容
* @param key: 阿里云文件名
* @return
* @throws IOException
*/
public static String uploadBase64Pdf2OSS(String pdfBase64Content, String key) {
InputStream in = null;
try {
if (pdfBase64Content != null) {
BASE64Decoder decoder = new BASE64Decoder();
pdfBase64Content = pdfBase64Content.replace("data:application/pdf;base64,", "");
pdfBase64Content = pdfBase64Content.replace(" ", "+").replace("\r\n", "");
byte[] content = decoder.decodeBuffer(pdfBase64Content);
for (int i = 0; i < content.length; ++i) {
if (content[i] < 0) {// 調(diào)整異常數(shù)據(jù)
content[i] += 256;
}
}
in = new ByteArrayInputStream(content);
return uploadFile2OSS(key, in, CONTENT_TYPE_PDF);
} else {
return null;
}
} catch (Exception e) {
logger.error("uploadImg2OSS failed:" + e.getMessage());
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
}
}
}
}
/**
* fileType有以下取值
* 1: excel
* 2: txt
* 3: csv
* 4: pdf
* 5:jpeg
* @param content
* @param key
* @param fileType
* @return
*/
public static String uploadBase64Content2OSS(String content, String key, int fileType) {
InputStream in = null;
try {
if (content != null) {
String fileContentPrefix = null;
if (content.startsWith("data")) {
int index = content.indexOf(",");
fileContentPrefix = content.substring(0, index);
content = content.substring(index+1,content.length());
}
Map<String, String> suffixMap = determineFileSuffix(fileContentPrefix, fileType);
BASE64Decoder decoder = new BASE64Decoder();
content = content.replace(" ", "+").replace("\r\n", "");
byte[] contentBytes = decoder.decodeBuffer(content);
for (int i = 0; i < contentBytes.length; ++i) {
if (contentBytes[i] < 0) {// 調(diào)整異常數(shù)據(jù)
contentBytes[i] += 256;
}
}
in = new ByteArrayInputStream(contentBytes);
return uploadFile2OSS(key+suffixMap.get("suffix"), in, suffixMap.get("contentType"));
} else {
return null;
}
} catch (Exception e) {
logger.error("uploadImg2OSS failed:" + e.getMessage());
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
}
}
}
}
/**
* 將微信文件上傳至阿里云OSS
* @param serverId:網(wǎng)絡(luò)文件URL
* @param key:文件名
* @return
*/
public static String uploadWXContent2OSS(String serverId, String key, String wxAccessToken, String contentType){
InputStream inputStream = null;
try {
String urlString = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
+ wxAccessToken
+ "&media_id="
+ serverId;
return uploadURLContent2OSS(urlString, key, contentType);
} catch (Exception e) {
logger.error("uploadImg2OSS failed:" + e.getMessage());
e.printStackTrace();
}finally{
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception ex) {
}
}
}
return null;
}
/**
* 上傳文件至阿里云
* @param xmlContent:待上傳圖片Base64字符串內(nèi)容
* @param key: 阿里云文件名
* @return
* @throws IOException
*/
public static String uploadXML2OSS(String xmlContent, String key) {
InputStream in = null;
InputStream output = null;
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
byte[] data = null;
try {
if (StringUtils.isNotBlank(xmlContent)) {
in = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
/**
* 根據(jù)實(shí)際運(yùn)行效果 設(shè)置緩沖區(qū)大小
*/
byte[] buffer=new byte[1024 * 100];
int ch = 0;
while ((ch = in.read(buffer)) != -1) {
bytesOut.write(buffer,0,ch);
}
data = bytesOut.toByteArray();
output = new ByteArrayInputStream(data);
return uploadFile2OSS(key, output, CONTENT_TYPE_TXT);
} else {
return null;
}
} catch (Exception e) {
logger.error("uploadXML2OSS failed:" + e.getMessage());
return null;
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
}
}
if (output != null) {
try {
output.close();
} catch (Exception ex) {
}
}
if (bytesOut != null) {
try {
bytesOut.close();
} catch (Exception ex) {
}
}
}
}
/**
* 上傳分片文件至阿里云
* @param file
* @param key
* @return
* @throws IOException
*/
public static String uploadImg2OSS(MultipartFile file, String key){
String urlString = null;
try {
urlString = uploadFile2OSS(key,file.getInputStream(), CONTENT_TYPE_IMAGE);
} catch (Exception e) {
e.printStackTrace();
}
return urlString;
}
/**
* 上傳本地文件到阿里云OSS中
* @param filePath:本地文件完整文件名(含路徑)
* @return
*/
public static String uploadLocalImg2OSS(String filePath, String key) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
String uploadImg2OSS = uploadFile2OSS(key, inputStream, CONTENT_TYPE_IMAGE);
return uploadImg2OSS;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception ex) {
}
}
}
}
/**
* 將網(wǎng)絡(luò)流文件上傳至阿里云OSS
* @param url:網(wǎng)絡(luò)文件URL
* @param key:文件名
* @return
*/
public static String uploadURLImg2OSS(String url, String key){
InputStream inputStream = null;
InputStream output = null;
try {
byte[] content = HttpUtil.downloadFile(url);
if(content == null)
return null;
output = new ByteArrayInputStream(content);
return uploadFile2OSS(key, output, CONTENT_TYPE_IMAGE);
} catch (Exception e) {
logger.error("uploadImg2OSS failed:" + e.getMessage());
e.printStackTrace();
}finally{
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception ex) {
}
}
if (output != null) {
try {
output.close();
} catch (Exception ex) {
}
}
}
return null;
}
public static String uploadURLContent2OSS(String url, String key, String contentType){
InputStream inputStream = null;
InputStream output = null;
try {
byte[] content = HttpUtil.downloadFile(url);
if(content == null)
return null;
output = new ByteArrayInputStream(content);
return uploadFile2OSS(key, output, contentType);
} catch (Exception e) {
logger.error("uploadImg2OSS failed:" + e.getMessage());
e.printStackTrace();
}finally{
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception ex) {
}
}
if (output != null) {
try {
output.close();
} catch (Exception ex) {
}
}
}
return null;
}
/**
* 將微信文件上傳至阿里云OSS
* @param serverId:網(wǎng)絡(luò)文件URL
* @param key:文件名
* @return
*/
public static String uploadWXImg2OSS(String serverId, String key, String wxAccessToken){
InputStream inputStream = null;
try {
String urlString = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
+ wxAccessToken
+ "&media_id="
+ serverId;
return uploadURLImg2OSS(urlString, key);
} catch (Exception e) {
logger.error("uploadImg2OSS failed:" + e.getMessage());
e.printStackTrace();
}finally{
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception ex) {
}
}
}
return null;
}
/**
* @Title: uploadLocalExecl2OSS
* @Description: 上傳本地excel文件到阿里云OSS中
* @param filePath 文件的路徑
* @param key 文件名稱
* @return String excel文件訪問(wèn)地址
* @throws
*/
public static String uploadLocalExecl2OSS(String filePath, String key) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(filePath);
String urlString = uploadFile2OSS(key, inputStream, CONTENT_TYPE_EXECL);
logger.info("method[uploadLocalExecl2OSS] return url is: " + urlString);
return urlString;
} catch (Exception e) {
logger.error("method[uploadLocalExecl2OSS] ,異常為:" + e);
e.printStackTrace();
return null;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {}
}
}
}
/*****
* 將文件上傳到阿里云
* @param key:阿里文件名
* @param in:文件輸入流
* @return 阿里云訪問(wèn)URL
*/
private static String uploadFile2OSS(String key, InputStream in, String contentType){
ObjectMetadata objectMetadata = new ObjectMetadata();
try {
objectMetadata.setContentLength(in.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(contentType);
ossClient.putObject(bucketName, key, in, objectMetadata);
String urlString = getAccessURL(key);
logger.info("method[uploadFile2OSS] return url is: " + urlString + ", and key is: " + key);
return urlString;
} catch (Exception e) {
logger.error("alioss put object failed:" + e);
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/****
*
* @param key
* @return
*/
public static String getAccessURL(String key){
Date expiration = new Date(new Date().getTime() + 3600 * 1000 * 24 * 365 * 100); //100年
URL url = ossClientUrl.generatePresignedUrl(bucketName, key, expiration);
String urlString = url.toString();
urlString = urlString.substring(0,urlString.indexOf("?"));//截人馄恰芋齿?之前的內(nèi)容锣尉,減少空間占用
logger.info("url: "+urlString);
return urlString;
}
/**
* Description: 判斷OSS服務(wù)文件上傳時(shí)文件的contentType
*
* @param FilenameExtension 文件后綴
* @return String
*/
public static String getcontentType(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")) {
return "image/jpeg";
}
if (FilenameExtension.equalsIgnoreCase("html")) {
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";
}
return "image/jpeg";
}
/**
* 解析base64編碼的文件,獲取文件后綴名和contentType
* @param fileContentPrefix
* @param fileType
* @return
*/
public static Map<String,String> determineFileSuffix(String fileContentPrefix,Integer fileType) {
Map<String, String> map = new HashMap<String, String>();
if (fileType == 1) {//excel
map.put("contentType", "application/vnd.ms-excel");
if (fileContentPrefix != null && fileContentPrefix.contains("vnd.ms-excel")) {
map.put("suffix", ".xls");
}else {
map.put("suffix", ".xlsx");
}
} else if (fileType == 2) {//txt
map.put("contentType", "text/plain");
map.put("suffix", ".txt");
} else if (fileType == 3) {//csv
map.put("contentType", "application/vnd.ms-excel");
map.put("suffix", ".csv");
} else if (fileType == 4) {//pdf
map.put("contentType", "application/pdf");
map.put("suffix", ".pdf");
} else if (fileType == 5) {//image
map.put("contentType", "image/jpeg");
if (fileContentPrefix != null) {
if (fileContentPrefix.contains("jpeg")) {
map.put("suffix", ".jpg");
} else if (fileContentPrefix.contains("png")) {
map.put("suffix", ".png");
} else if (fileContentPrefix.contains("gif")) {
map.put("suffix", ".gif");
} else if (fileContentPrefix.contains("bmp")) {
map.put("suffix", ".bmp");
}
} else {
map.put("suffix", ".jpg");
}
} else if (fileType == 6) {
map.put("contentType", "application/vnd.ms-excel");
map.put("suffix", ".xls");
}
else {
map.put("contentType", "image/jpeg");
map.put("suffix", ".jpg");
}
return map;
}
public static Map<String,String> determineFileSuffixByFileType(Integer fileType) {
Map<String, String> map = new HashMap<String, String>();
if (fileType == 1) {//excel
map.put("contentType", "application/vnd.ms-excel");
map.put("suffix", ".xls");
} else if (fileType == 2) {//txt
map.put("contentType", "text/plain");
map.put("suffix", ".txt");
} else if (fileType == 3) {//csv
map.put("contentType", "application/vnd.ms-excel");
map.put("suffix", ".csv");
} else if (fileType == 4) {//pdf
map.put("contentType", "application/pdf");
map.put("suffix", ".pdf");
} else if (fileType == 5) {//image
map.put("contentType", "image/jpeg");
map.put("suffix", ".jpg");
}else {
map.put("contentType", "image/jpeg");
map.put("suffix", ".jpg");
}
return map;
}
/****
*
* @param argc
*/
public static void main(String argc[]){
String endPoint = "http://oss-cn-beijing.aliyuncs.com/";
String accessKeyId = "LTAIK9ll0KNxPuDa";
String accessSecret = "ALESaVe9ldDffrjHS1e3eXtlu0owFg";
String bucketName = "sunshinetest";
// String fileURL = "http://n.sinaimg.cn/news/transform/20170823/In0W-fykcypq4080200.jpg";
// String strContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><簡(jiǎn)歷信息><簡(jiǎn)歷完整度>70</簡(jiǎn)歷完整度><郵件地址>125323338@qq.com</郵件地址><電話號(hào)碼>18505013700</電話號(hào)碼><二度好友數(shù)量>0</二度好友數(shù)量><一度好友數(shù)量>0</一度好友數(shù)量><關(guān)注獵頭數(shù)>0</關(guān)注獵頭數(shù)><行業(yè)編碼>500</行業(yè)編碼><行業(yè)名稱>信托/擔(dān)保/拍賣/典當(dāng)</行業(yè)名稱><薪資>20000</薪資><薪資月數(shù)>12</薪資月數(shù)><工作年限>6</工作年限><工作地點(diǎn)名稱>福州</工作地點(diǎn)名稱><工作地點(diǎn)編碼>090020</工作地點(diǎn)編碼><學(xué)歷信息><畢業(yè)時(shí)間>201707</畢業(yè)時(shí)間><學(xué)歷編碼>40</學(xué)歷編碼><學(xué)歷名稱>本科</學(xué)歷名稱><入學(xué)時(shí)間>201207</入學(xué)時(shí)間><是否統(tǒng)招>0</是否統(tǒng)招><學(xué)校名稱>西安交通</學(xué)校名稱></學(xué)歷信息><學(xué)歷信息><畢業(yè)時(shí)間>201207</畢業(yè)時(shí)間><學(xué)歷編碼>50</學(xué)歷編碼><學(xué)歷名稱>大專</學(xué)歷名稱><入學(xué)時(shí)間>200907</入學(xué)時(shí)間><是否統(tǒng)招>1</是否統(tǒng)招><學(xué)校名稱>福建交通</學(xué)校名稱></學(xué)歷信息><工作經(jīng)歷><公司名稱>北京玖富時(shí)代投資顧問(wèn)有限公司</公司名稱><公司行業(yè)編碼>500</公司行業(yè)編碼><公司行業(yè)名稱>信托/擔(dān)保/拍賣/典當(dāng)</公司行業(yè)名稱><結(jié)束時(shí)間>201707</結(jié)束時(shí)間><開(kāi)始時(shí)間>201403</開(kāi)始時(shí)間><職稱>經(jīng)理</職稱></工作經(jīng)歷></簡(jiǎn)歷信息>";
OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessSecret);
OSSClientUtil.setOssClient(ossClient);
OSSClientUtil.setBucketName(bucketName);
try{
// OSSClientUtil.uploadURLImg2OSS(new URL(fileURL), "test1234.jpg");
File path = new File("D:\\data1\\jianli");
File[] listFiles = path.listFiles();
for (File file : listFiles) {
String key = file.getName();
System.out.println(key);
InputStream in = new FileInputStream(file);
String accessUrl = uploadFile2OSS(key, in, "CONTENT_TYPE_TXT");
System.out.println(accessUrl);
}
// OSSClientUtil.uploadXML2OSS(strContent, "resume.xml");
}catch(Exception e){
e.printStackTrace();
}
}
}