描述:oss比較方便,省去了本身搭建文件服務器的時間,價格比較便宜,下面是java基於oss的簡單上傳代碼java
a、添加maven依賴服務器
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.1.0</version> </dependency>
b、java代碼maven
public class TestOSSUpload { private static String endpoint = "http://oss-cn-shanghai.aliyuncs.com"; private static String accessKeyId = "你的accessKeyId "; private static String accessKeySecret = "你的accessKeySecret"; private static String bucketName = "你的bucket"; public void putObject(String bucketName, String key, String filePath) throws FileNotFoundException { // 初始化OSSClient OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret); // 獲取指定文件的輸入流 File file = new File(filePath); InputStream content = new FileInputStream(file); // 建立上傳Object的Metadata ObjectMetadata meta = new ObjectMetadata(); // 必須設置ContentLength meta.setContentLength(file.length()); Date expire = new Date(new Date().getTime() + 30 * 1000); meta.setExpirationTime(expire); // 上傳Object. PutObjectResult result = client.putObject(bucketName, key, content, meta); // 打印ETag System.out.println("etag--------------->"+result.getETag()); } public static void main(String[] args) throws FileNotFoundException { TestOSSUpload testOSSUpload = new TestOSSUpload(); testOSSUpload.putObject(bucketName, "temp3.xlsx", "D:\\temp.xlsx"); File file = new File("D:\\temp.xlsx"); String md5 = testOSSUpload.getFileMD5(file); System.out.println("md5---------------->"+md5); } public static String getFileMD5(File file) { if (!file.isFile()){ return null; } MessageDigest digest = null; FileInputStream in=null; byte buffer[] = new byte[1024]; int len; try { digest = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer, 0, 1024)) != -1) { digest.update(buffer, 0, len); } in.close(); } catch (Exception e) { e.printStackTrace(); return null; } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16).toUpperCase(); } }
致此結束…… blog
關注個人公衆號,精彩內容不能錯過md5