首页 > 代码库 > 阿里云OSS上传文件模块

阿里云OSS上传文件模块

  1 package com.hughes.bcsc.app.core.util.oss;
  2 
  3 import java.io.ByteArrayInputStream;
  4 import java.io.ByteArrayOutputStream;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.FileNotFoundException;
  8 import java.io.IOException;
  9 import java.io.InputStream;
 10 import java.net.URL;
 11 import java.util.Date;
 12 
 13 import javax.imageio.stream.FileImageInputStream;
 14 
 15 import org.apache.log4j.Logger;
 16 import org.springframework.stereotype.Component;
 17 
 18 import com.aliyun.oss.OSSClient;
 19 import com.aliyun.oss.model.Bucket;
 20 import com.aliyun.oss.model.OSSObject;
 21 import com.aliyun.oss.model.ObjectMetadata;
 22 import com.aliyun.oss.model.PutObjectResult;
 23 
 24 import sun.misc.BASE64Decoder;
 25 
 26 /**
 27  * 
 28 * @ClassName: AliyunOSSClientUtil 
 29 * @Description: 阿里云OSS上传文件模块 
 30 * @author wy
 31 * @date 2017年5月6日 下午6:01:46 
 32 *
 33  */
 34 @Component
 35 public class AliyunOSSClientUtil {
 36     // log日志
 37     private static Logger logger = Logger.getLogger(AliyunOSSClientUtil.class);
 38     // 阿里云API的内或外网域名
 39     private static String ENDPOINT;
 40     // 阿里云API的密钥Access Key ID
 41     private static String ACCESS_KEY_ID;
 42     // 阿里云API的密钥Access Key Secret
 43     private static String ACCESS_KEY_SECRET;
 44     // 阿里云API的bucket名称
 45     public static String BACKET_NAME;
 46     // 阿里云API的文件夹名称
 47     private static String FOLDER;
 48     private static String FORMAT;
 49     private static String FORMATS;
 50     private static String FOLDER_VIDEO;
 51 
 52     // 初始化属性
 53     static {
 54         ENDPOINT = OSSClientConstants.ENDPOINT;
 55         ACCESS_KEY_ID = OSSClientConstants.ACCESS_KEY_ID;
 56         ACCESS_KEY_SECRET = OSSClientConstants.ACCESS_KEY_SECRET;
 57         BACKET_NAME = OSSClientConstants.BACKET_NAME;
 58         FOLDER = OSSClientConstants.FOLDER;
 59         FORMAT = OSSClientConstants.FORMAT;
 60         FORMATS = OSSClientConstants.FORMATS;
 61         FOLDER_VIDEO = OSSClientConstants.FOLDER_VIDEO;
 62     }
 63 
 64     /**
 65      * 获取阿里云OSS客户端对象
 66      * 
 67      * @return ossClient
 68      */
 69     public static OSSClient getOSSClient() {
 70         return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
 71     }
 72 
 73     /**
 74      * 创建存储空间
 75      * 
 76      * @param ossClient
 77      *            OSS连接
 78      * @param bucketName
 79      *            存储空间
 80      * @return
 81      */
 82     public static String createBucketName(OSSClient ossClient, String bucketName) {
 83         // 存储空间
 84         final String bucketNames = bucketName;
 85         if (!ossClient.doesBucketExist(bucketName)) {
 86             // 创建存储空间
 87             Bucket bucket = ossClient.createBucket(bucketName);
 88             logger.info("创建存储空间成功");
 89             return bucket.getName();
 90         }
 91         return bucketNames;
 92     }
 93 
 94     /**
 95      * 删除存储空间buckName
 96      * 
 97      * @param ossClient
 98      *            oss对象
 99      * @param bucketName
100      *            存储空间
101      */
102     public static void deleteBucket(OSSClient ossClient, String bucketName) {
103         ossClient.deleteBucket(bucketName);
104         logger.info("删除" + bucketName + "Bucket成功");
105     }
106 
107     /**
108      * 创建模拟文件夹
109      * 
110      * @param ossClient
111      *            oss连接
112      * @param bucketName
113      *            存储空间
114      * @param folder
115      *            模拟文件夹名如"qj_nanjing/"
116      * @return 文件夹名
117      */
118     public static String createFolder(OSSClient ossClient, String bucketName, String folder) {
119         // 文件夹名
120         final String keySuffixWithSlash = folder;
121         // 判断文件夹是否存在,不存在则创建
122         if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
123             // 创建文件夹
124             ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
125             logger.info("创建文件夹成功");
126             // 得到文件夹名
127             OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
128             String fileDir = object.getKey();
129             return fileDir;
130         }
131         return keySuffixWithSlash;
132     }
133 
134     /**
135      * 根据key删除OSS服务器上的文件
136      * 
137      * @param ossClient
138      *            oss连接
139      * @param bucketName
140      *            存储空间
141      * @param folder
142      *            模拟文件夹名 如"qj_nanjing/"
143      * @param key
144      *            Bucket下的文件的路径名+文件名 如:"upload/cake.jpg"
145      */
146     public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key) {
147         ossClient.deleteObject(bucketName, folder + key);
148         logger.info("删除" + bucketName + "下的文件" + folder + key + "成功");
149     }
150 
151     /**
152      * 上传图片至OSS 文件流
153      * 
154      * @param ossClient
155      *            oss连接
156      * @param file
157      *            上传文件(文件全路径如:D:\\image\\cake.jpg)
158      * @param bucketName
159      *            存储空间
160      * @param folder
161      *            模拟文件夹名 如"qj_nanjing/"
162      * @return String 返回的唯一MD5数字签名
163      */
164     public static String[] uploadObject2OSS(OSSClient ossClient, File file, String bucketName, String user_id) {
165         String resultStr = null;
166         String[] fo = new String[] { "", "" };
167         try {
168             // 以输入流的形式上传文件
169             String folder = "";
170             folder = FOLDER + user_id + "/" + FORMAT + "/";
171             InputStream is = new FileInputStream(file);
172             // 文件名
173             String timefile = FORMATS;
174             String fileName = file.getName();
175             fileName = timefile + fileName.substring(fileName.lastIndexOf("."));
176             logger.info("上传到路径" + folder + fileName);
177             // 文件大小
178             Long fileSize = file.length();
179             // 创建上传Object的Metadata
180             ObjectMetadata metadata = http://www.mamicode.com/new ObjectMetadata();
181             // 上传的文件的长度
182             metadata.setContentLength(is.available());
183             // 指定该Object被下载时的网页的缓存行为
184             metadata.setCacheControl("no-cache");
185             // 指定该Object下设置Header
186             metadata.setHeader("Pragma", "no-cache");
187             // 指定该Object被下载时的内容编码格式
188             metadata.setContentEncoding("utf-8");
189             // 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
190             // 如果没有扩展名则填默认值application/octet-stream
191             metadata.setContentType(getContentType(fileName));
192             // 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
193             metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
194             // 上传文件 (上传文件流的形式)
195             PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, is, metadata);
196             // 解析结果
197             resultStr = putResult.getETag();
198             fo[1] = folder + fileName;
199             fo[0] = resultStr;
200 
201             ossClient.shutdown();
202         } catch (Exception e) {
203             e.printStackTrace();
204             logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
205         }
206         return fo;
207     }
208     //上传路径返回地址,图片视频都可以
209     //需要改变上传那文件位置FOLDER
210     public static String[] uploadObjectOSS(OSSClient ossClient, String file, String bucketName, String user_id) {
211         String resultStr = null;
212         String[] fo = new String[] { "", "" };
213         try {
214             // 以输入流的形式上传文件
215             String folder = "";
216             folder = FOLDER + user_id + "/" + FORMAT + "/";
217 //            InputStream is = new FileInputStream(file);
218             // 文件名
219             String timefile = FORMATS;
220 //            String fileName = file.getName();
221             file = timefile + file.substring(file.lastIndexOf("."));
222             logger.info("上传到路径" + folder + file);
223             // 文件大小
224             Integer fileSize = file.length();
225             // 创建上传Object的Metadata
226             ObjectMetadata metadata = http://www.mamicode.com/new ObjectMetadata();
227 //            // 上传的文件的长度
228 //            metadata.setContentLength(is.available());
229             // 指定该Object被下载时的网页的缓存行为
230             metadata.setCacheControl("no-cache");
231             // 指定该Object下设置Header
232             metadata.setHeader("Pragma", "no-cache");
233             // 指定该Object被下载时的内容编码格式
234             metadata.setContentEncoding("utf-8");
235             // 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
236             // 如果没有扩展名则填默认值application/octet-stream
237             metadata.setContentType(getContentType(file));
238             // 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
239             metadata.setContentDisposition("filename/filesize=" + file + "/" + fileSize + "Byte.");
240             // 上传文件 (上传文件流的形式)
241             PutObjectResult putResult = ossClient.putObject(bucketName, folder + file, new ByteArrayInputStream(file.getBytes("UTF-8")), metadata);
242             // 解析结果
243             resultStr = putResult.getETag();
244             fo[1] = folder + file;
245             fo[0] = resultStr;
246 
247             ossClient.shutdown();
248         } catch (Exception e) {
249             e.printStackTrace();
250             logger.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
251         }
252         return fo;
253     }
254     //上传视频
255     public static String uploadByteVideoOSS(OSSClient ossClient, byte[] b, String bucketName, String user_id) {
256 
257         // byte[] content = "Hello OSS".getBytes();
258 
259         // 以输入流的形式上传文件
260         String folder = "";
261         folder = FOLDER_VIDEO + user_id + "/" + FORMAT + "/";
262         // 文件名
263         String timefile = FORMATS;// 文件名
264         String fileName = ".MP4";// 后缀扩展名
265         fileName = timefile + fileName;
266         logger.info("上传到路径" + folder + fileName);
267 
268         Long fileSize = (long) b.length;
269 
270         // 创建上传Object的Metadata
271         ObjectMetadata metadata = http://www.mamicode.com/new ObjectMetadata();
272         metadata.setContentLength(fileSize);
273         // 指定该Object被下载时的网页的缓存行为
274         metadata.setCacheControl("no-cache");
275         // 指定该Object下设置Header
276         metadata.setHeader("Pragma", "no-cache");
277         // 指定该Object被下载时的内容编码格式
278         metadata.setContentEncoding("utf-8");
279         // 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
280         // 如果没有扩展名则填默认值application/octet-stream
281         metadata.setContentType(getContentType(fileName));
282         // 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
283         metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
284 
285         PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, new ByteArrayInputStream(b),
286                 metadata);
287         ossClient.shutdown();
288         String filepath = folder + fileName;
289         return filepath;
290     }
291     //上传图片
292     public static String uploadByteOSS(OSSClient ossClient, byte[] b, String bucketName, String user_id) {
293 
294         // byte[] content = "Hello OSS".getBytes();
295 
296         // 以输入流的形式上传文件
297         String folder = "";
298         folder = FOLDER + user_id + "/" + FORMAT + "/";
299         // 文件名
300         String timefile = FORMATS;// 文件名
301         String fileName = ".jpg";// 后缀扩展名
302         fileName = timefile + fileName;
303         logger.info("上传到路径" + folder + fileName);
304 
305         Long fileSize = (long) b.length;
306 //        String timefile = FORMATS;
307 ////        String fileName = file.getName();
308 //        file = timefile + file.substring(file.lastIndexOf("."));
309         // 创建上传Object的Metadata
310         ObjectMetadata metadata = http://www.mamicode.com/new ObjectMetadata();
311         metadata.setContentLength(fileSize);
312         // 指定该Object被下载时的网页的缓存行为
313         metadata.setCacheControl("no-cache");
314         // 指定该Object下设置Header
315         metadata.setHeader("Pragma", "no-cache");
316         // 指定该Object被下载时的内容编码格式
317         metadata.setContentEncoding("utf-8");
318         // 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成,
319         // 如果没有扩展名则填默认值application/octet-stream
320         metadata.setContentType(getContentType(fileName));
321         // 指定该Object被下载时的名称(指示MINME用户代理如何显示附加的文件,打开或下载,及文件名称)
322         metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
323 
324         PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, new ByteArrayInputStream(b),
325                 metadata);
326         ossClient.shutdown();
327         String filepath = folder + fileName;
328         return filepath;
329     }
330 
331     public static byte[] image2Bytes(String imgSrc) throws Exception {
332         FileInputStream fin = new FileInputStream(new File(imgSrc));
333         // 可能溢出,简单起见就不考虑太多,如果太大就要另外想办法,比如一次传入固定长度byte[]
334         byte[] bytes = new byte[fin.available()];
335         // 将文件内容写入字节数组,提供测试的case
336         fin.read(bytes);
337 
338         fin.close();
339         return bytes;
340     }
341     //图片转化为byte数组
342     public static byte[] image2byte(String path) {
343         byte[] data = http://www.mamicode.com/null;
344         FileImageInputStream input = null;
345         try {
346             input = new FileImageInputStream(new File(path));
347             ByteArrayOutputStream output = new ByteArrayOutputStream();
348             byte[] buf = new byte[1024];
349             int numBytesRead = 0;
350             while ((numBytesRead = input.read(buf)) != -1) {
351                 output.write(buf, 0, numBytesRead);
352             }
353             data =http://www.mamicode.com/ output.toByteArray();
354             output.close();
355             input.close();
356         } catch (FileNotFoundException ex1) {
357             ex1.printStackTrace();
358         } catch (IOException ex1) {
359             ex1.printStackTrace();
360         }
361         return data;
362     }
363 
364     /**
365      * 通过文件名判断并获取OSS服务文件上传时文件的contentType
366      * 
367      * @param fileName
368      *            文件名
369      * @return 文件的contentType
370      */
371     public static String getContentType(String fileName) {
372         // 文件的后缀名
373         String fileExtension = fileName.substring(fileName.lastIndexOf("."));
374         if (".bmp".equalsIgnoreCase(fileExtension)) {
375             return "image/bmp";
376         }
377         if (".gif".equalsIgnoreCase(fileExtension)) {
378             return "image/gif";
379         }
380         if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
381                 || ".png".equalsIgnoreCase(fileExtension)) {
382             return "image/jpeg";
383         }
384         if (".html".equalsIgnoreCase(fileExtension)) {
385             return "text/html";
386         }
387         if (".txt".equalsIgnoreCase(fileExtension)) {
388             return "text/plain";
389         }
390         if (".vsd".equalsIgnoreCase(fileExtension)) {
391             return "application/vnd.visio";
392         }
393         if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
394             return "application/vnd.ms-powerpoint";
395         }
396         if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
397             return "application/msword";
398         }
399         if (".xml".equalsIgnoreCase(fileExtension)) {
400             return "text/xml";
401         }
402         if (".mp4".equalsIgnoreCase(fileExtension)) {
403             return "video/mp4";
404         }
405         // 默认返回类型
406         return "image/jpeg";
407     }
408 
409     /**
410      * 获得url链接
411      *
412      * @param key
413      * @return
414      */
415     public static String getUrl(OSSClient ossClient, String bucketName, String fileName) {
416         // 设置URL过期时间为10年 3600l* 1000*24*365*10
417         Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
418         // 生成URL
419         URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
420         if (url != null) {
421             return url.toString();
422         }
423         return "获网址路径出错";
424     }
425 
426     public String urlpath(String user_id, String files) {
427         OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
428         String[] file = files.split(",");
429         String url = "";
430         for (String filename : file) {
431             // System.out.println("filename:"+filename);
432             File filess = new File(filename);
433             String[] s = AliyunOSSClientUtil.uploadObject2OSS(ossClient, filess, BACKET_NAME, user_id);
434             logger.info("上传后的文件MD5数字唯一签名:" + s[0]);
435             logger.info("文件路径:" + s[1]);
436             url = AliyunOSSClientUtil.getUrl(ossClient, BACKET_NAME, s[1]);
437             logger.info("访问网址路径:" + url);
438         }
439         // 上传后的文件MD5数字唯一签名:40F4131427068E08451D37F02021473A
440         return url;
441     }
442     public String uploadvideo(String url){
443         String user_id="localism";
444         String[] urllist=AliyunOSSClientUtil.uploadObject2OSS(AliyunOSSClientUtil.getOSSClient(), new File(url), BACKET_NAME, user_id);
445         String c=urllist[1];
446         return c;
447     }
448     // 测试
449     public static void main(String[] args) throws Exception {
450         AliyunOSSClientUtil t = new AliyunOSSClientUtil();
451         String url = t.uploadvideo("g:\\余杰的avi小视频.mp4");
452         System.out.println(url);
453         /*// 初始化OSSClient
454         OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
455         // 上传文件
456         String files = "D:\\1.jpg";
457         String[] file = files.split(",");
458         String user_id = "3";
459         
460          * for (String filename : file) { //
461          * System.out.println("filename:"+filename); File filess = new
462          * File(filename); String[] s =
463          * AliyunOSSClientUtil.uploadObject2OSS(ossClient, filess, BACKET_NAME,
464          * user_id); logger.info("上传后的文件MD5数字唯一签名:" + s[0]); logger.info("文件路径:"
465          * + s[1]); String url = AliyunOSSClientUtil.getUrl(ossClient,
466          * BACKET_NAME, s[1]); logger.info("访问网址路径:" + url); //
467          * 上传后的文件MD5数字唯一签名:40F4131427068E08451D37F02021473A }
468          
469 
470         byte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VJRD0ieG1wLmlpZDo5QzY2OUNCMDg4MEYxMUUxODU4OUQ4M0REMkFGNTBBNCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo5QzY2OUNCMTg4MEYxMUUxODU4OUQ4M0REMkFGNTBBNCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PsQhXeAAAABfSURBVHjaYvz//z8DJYCRUgMYQAbAMBQIAvEqkBQWXI6sHqwHiwG70TTBxGaiWwjCTGgOUgJiF1J8wMRAIUA34B4Q76HUBelAfJYSA0CuMIEaRP8wGIkGMA54bgQIMACAmkXJi0hKJQAAAABJRU5ErkJggg==";
474          * BASE64Decoder decoder = new BASE64Decoder(); byte[] b =
475          * decoder.decodeBuffer(str);
476          * 
477          * System.out.println(b.length);
478          
479         
480 //        String path = AliyunOSSClientUtil.uploadByteVideoOSS(ossClient, b1, BACKET_NAME, user_id);
481         String path = AliyunOSSClientUtil.uploadByteOSS(ossClient, b1, BACKET_NAME, user_id);
482 //        String path = AliyunOSSClientUtil.uploadObjectOSS(ossClient, b1, BACKET_NAME, user_id);
483         System.out.println(b1.length + "," + b1.toString());
484         logger.info("文件路径:" + path);
485         String url = AliyunOSSClientUtil.getUrl(ossClient, BACKET_NAME, path);
486         logger.info("访问网址路径:" + url);*/
487     }
488 
489 }

上传代码获取路径和处理路径

阿里云OSS上传文件模块