コード例 #1
0
ファイル: LearnOss.java プロジェクト: xinkunZ/AliyunStudy
  public static void main(String[] args) throws IOException {

    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    try {
      // createBuket("create-by-code", client);
      // UploadMethod.sendStr("create-by-code", "Hello OSS!", client);
      // UploadMethod.uploadFile("create-by-code", new File("c:/hello oss.txt"),
      // client);
      // UploadMethod.uploadFileProgress(bucketName, new File(
      // "E:/MOVE/Videos/神探夏洛克-恐怖的新娘/Sherlock Abominable Bride 2015 720p.mkv"),
      // client);
      // UploadMethod.createDir(bucketName, "新建文件夹", client);
      // UploadMethod.createDir(bucketName, "新建文件夹/a", client);
      // UploadMethod.uploadFile(bucketName, new File("c:/test.txt"),
      // "新建文件夹/a/", client);
      // DownloadMethod.readContent(bucketName, "Hello OSS!", client);
      // DownloadMethod.downloadFile(bucketName, client, "新建文件夹/a/test.txt");
      // OpratorMethod.listBucket(client);
      OpratorMethod.listObj(bucketName, client);
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      client.shutdown();
    }
  }
 public static void main(String[] args) {
   OSSClient client = new OSSClient(OSS_ENDPOINT, ACCESS_ID, ACCESS_KEY);
   String bucketName = OSSConfig.BUCKET_NAME;
   try {
     String location = client.getBucketLocation(bucketName);
     System.out.println(location);
   } catch (OSSException e) {
     e.printStackTrace();
   }
 }
コード例 #3
0
  /**
   * 下载文件
   *
   * @author [email protected]
   * @param fileId
   * @return
   * @throws IOException
   */
  public FileInfo download(String fileId) throws IOException {
    logger.debug("download file from OSS--start");
    if (fileId == null || fileId.equals("")) {
      throw new IllegalArgumentException("fileId不能为null或者空字符串");
    }
    OSSClient client = this.getOSSClient();
    OSSObject ossObject = client.getObject(bucketName, fileId);
    FileInfo fileInfo = new FileInfo();
    InputStream is = ossObject.getObjectContent();
    byte[] content = IOUtils.readStreamAsByteArray(is);
    checkContent(content);
    ObjectMetadata objectMetadata = ossObject.getObjectMetadata();
    String fileName = objectMetadata.getUserMetadata().get("filename");
    fileInfo.setFileContent(content);
    fileInfo.setFileName(fileName);

    logger.debug("download file from OSS--end");
    return fileInfo;
  }
コード例 #4
0
 public static void readContent(String bucketName, String key, OSSClient client)
     throws IOException {
   BufferedReader br = null;
   try {
     OSSObject objec = client.getObject(bucketName, key);
     br = new BufferedReader(new InputStreamReader(objec.getObjectContent()));
     String line = br.readLine();
     while (line != null) {
       System.out.println(line);
       line = br.readLine();
     }
     System.out.println("读完啦!");
   } catch (Exception e) {
     System.err.println(e);
   } finally {
     br.close();
   }
 }
コード例 #5
0
  public static void main(String[] args) throws IOException {
    /*
     * Constructs a client instance with your account for accessing OSS
     */
    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    try {
      /*
       * Append an object from specfied input stream, keep in mind that
       * position should be set to zero at first time.
       */
      String content = "Thank you for using Aliyun Object Storage Service";
      InputStream instream = new ByteArrayInputStream(content.getBytes());
      Long firstPosition = 0L;
      System.out.println("Begin to append object at position(" + firstPosition + ")");
      AppendObjectResult appendObjectResult =
          client.appendObject(new AppendObjectRequest(bucketName, key, instream).withPosition(0L));
      System.out.println(
          "\tNext position="
              + appendObjectResult.getNextPosition()
              + ", CRC64="
              + appendObjectResult.getObjectCRC()
              + "\n");

      /*
       * Continue to append the object from specfied file descriptor at last position
       */
      Long nextPosition = appendObjectResult.getNextPosition();
      System.out.println("Continue to append object at last position(" + nextPosition + "):");
      appendObjectResult =
          client.appendObject(
              new AppendObjectRequest(bucketName, key, createTempFile())
                  .withPosition(nextPosition));
      System.out.println(
          "\tNext position="
              + appendObjectResult.getNextPosition()
              + ", CRC64="
              + appendObjectResult.getObjectCRC());

      /*
       * View object type of the appendable object
       */
      OSSObject object = client.getObject(bucketName, key);
      System.out.println("\tObject type=" + object.getObjectMetadata().getObjectType() + "\n");
      // Do not forget to close object input stream if not use it any more
      object.getObjectContent().close();

      /*
       * Delete the appendable object
       */
      System.out.println("Deleting an appendable object");
      client.deleteObject(bucketName, key);

    } catch (OSSException oe) {
      System.out.println(
          "Caught an OSSException, which means your request made it to OSS, "
              + "but was rejected with an error response for some reason.");
      System.out.println("Error Message: " + oe.getErrorCode());
      System.out.println("Error Code:       " + oe.getErrorCode());
      System.out.println("Request ID:      " + oe.getRequestId());
      System.out.println("Host ID:           " + oe.getHostId());
    } catch (ClientException ce) {
      System.out.println(
          "Caught an ClientException, which means the client encountered "
              + "a serious internal problem while trying to communicate with OSS, "
              + "such as not being able to access the network.");
      System.out.println("Error Message: " + ce.getMessage());
    } finally {
      /*
       * Do not forget to shut down the client finally to release all allocated resources.
       */
      client.shutdown();
    }
  }
コード例 #6
0
  /**
   * 上传文件
   *
   * @author [email protected]
   * @param filename:文件名称
   * @param content:文件的内容,用字节数组存储
   * @return 文件在OSS中的唯一标识,即fileId
   */
  public String upload(String filename, byte[] content) {
    logger.debug("upload file to OSS--start");
    if (content == null || content.length == 0) {
      throw new IllegalArgumentException("文件内容不能为空");
    }
    OSSClient client = this.getOSSClient();
    String key = UUIDUtils.getUUID();

    ObjectMetadata meta = new ObjectMetadata();
    Map<String, String> userMetadata = new HashMap<String, String>();
    if (filename == null || filename.equals("")) {
      filename = key;
    }
    logger.debug("filename:" + filename);
    userMetadata.put("filename", filename);
    meta.setUserMetadata(userMetadata);
    // 开始Multipart Upload
    InitiateMultipartUploadRequest initiateMultipartUploadRequest =
        new InitiateMultipartUploadRequest(bucketName, key, meta);
    InitiateMultipartUploadResult initiateMultipartUploadResult =
        client.initiateMultipartUpload(initiateMultipartUploadRequest);

    logger.debug("UploadId: " + initiateMultipartUploadResult.getUploadId());

    // 设置每块为 5M
    final int partSize = 1024 * 1024 * 5;
    // 计算分块数目
    int partCount = (int) (content.length / partSize);
    if (content.length % partSize != 0) {
      partCount++;
    }
    // 新建一个List保存每个分块上传后的ETag和PartNumber
    List<PartETag> partETags = new ArrayList<PartETag>();
    for (int i = 0; i < partCount; i++) {
      InputStream partIs = new ByteArrayInputStream(content);
      // 计算每个分块的大小
      int size =
          partSize < content.length - i * partSize ? partSize : content.length - i * partSize;
      byte[] copy = new byte[size];
      System.arraycopy(content, partSize * i, copy, 0, size);
      // 创建UploadPartRequest,上传分块
      UploadPartRequest uploadPartRequest = new UploadPartRequest();
      uploadPartRequest.setBucketName(bucketName);
      uploadPartRequest.setKey(key);
      uploadPartRequest.setUploadId(initiateMultipartUploadResult.getUploadId());
      uploadPartRequest.setInputStream(partIs);
      uploadPartRequest.setPartSize(size);
      uploadPartRequest.setPartNumber(i + 1);
      UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
      // 将返回的PartETag保存到List中
      partETags.add(uploadPartResult.getPartETag());
    }
    CompleteMultipartUploadRequest completeMultipartUploadRequest =
        new CompleteMultipartUploadRequest(
            bucketName, key, initiateMultipartUploadResult.getUploadId(), partETags);
    // 完成分块上传
    CompleteMultipartUploadResult completeMultipartUploadResult =
        client.completeMultipartUpload(completeMultipartUploadRequest);
    logger.debug("ETag:" + completeMultipartUploadResult.getETag());
    logger.debug("文件的key:" + key);
    logger.debug("upload file to OSS--end");
    return key;
  }
コード例 #7
0
 public static void downloadFile(String bucketName, OSSClient client, String key) {
   GetObjectRequest request = new GetObjectRequest(bucketName, key);
   client.getObject(request, new File("c:/test_down.txt"));
 }