根據阿里雲的OSS服務上傳圖片以及檔案
阿新 • • 發佈:2019-01-30
/** * 阿里雲oss檔案上傳工具類 * Created by gz on 2017/10/25. * qq:1293443962 */ public class OssUtil { private static Logger logger = Logger.getLogger(OssUtil.class); private static String bucket_name = "申請自己的oss"; private static String bucket_source = "oss-cn-beijing.aliyuncs.com"; private static String accessKeyId = "申請自己的oss"; private static String secretAccessKey = "申請自己的oss"; /** * 檔案上傳 * * @param filepath 本地地址 * @return */ public static String getOSSUrl(String filepath) { try { File file = new File(filepath); String file_name = filepath.split("/")[filepath.split("/").length - 1]; String OssUrl = null; if (file.exists() && file.length() > 0) { OssUrl = OssUtil.getOssFilePath(file_name, filepath); } return OssUrl; } catch (Exception e) { e.printStackTrace(); return null; } } private static String getOssFilePath(String fileName, String uploadFilePath) { URL uri = null; OSSClient client = getOSSUitl(); //上傳圖片 String key = "image/" + fileName; //指定檔案上傳到bucket下面的那個資料夾下及檔名 Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10); boolean isSuccess = uploadFile(client, bucket_name, key, uploadFilePath);//指定bucket if (isSuccess) { uri = client.generatePresignedUrl(bucket_name, key, expiration); } return uri.toString(); } private static boolean uploadFile(OSSClient client, String bucketName, String key, String filePath) { int MAX_TRY = 3; int downloadTurn = 0; boolean uploadSuccess = false; while (downloadTurn < MAX_TRY) { try { File file = new File(filePath); if ((!file.exists()) || file.length() == 0) { uploadSuccess = false; break; } ObjectMetadata objectMeta = new ObjectMetadata(); objectMeta.setContentLength(file.length()); if (!client.doesObjectExist(bucketName, key)) { InputStream input = new FileInputStream(file); client.putObject(bucketName, key, input, objectMeta); System.out.println(filePath + "上傳成功!"); uploadSuccess = true; break; } else { uploadSuccess = true; break; } } catch (Exception e) { e.printStackTrace(); } } return uploadSuccess; } /** * 刪除指定檔案 * * @param folder 檔名 * @param key 檔名 */ public static void deleteOSSFileUitl(String folder, String key) { OSSClient ossClient = getOSSUitl(); ossClient.deleteObject(bucket_name, folder + key); logger.info("刪除" + bucket_name + "下檔案" + folder + key + "成功"); System.out.println("刪除" + bucket_name + "下檔案" + folder + key + "成功"); }