阿里雲oss,簡單上傳


描述:oss比較方便,省去了自己搭建文件服務器的時間,價格比較便宜,下面是java基於oss的簡單上傳代碼

a、添加maven依賴

<dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>2.1.0</version>
</dependency>

b、java代碼

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();
	  }
	
}

致此結束……  

 

 

關注我的公眾號,精彩內容不能錯過


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM