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

致此结束……  

 

关注我的公众号,精彩内容不能错过

原文地址:https://www.cnblogs.com/huanchupkblog/p/5794095.html