com.aliyun.oss.model.PutObjectRequest Java Examples

The following examples show how to use com.aliyun.oss.model.PutObjectRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UploadController.java    From MyShopPlus with Apache License 2.0 6 votes vote down vote up
/**
 * 文件上传
 *
 * @param multipartFile @{code MultipartFile}
 * @return {@link ResponseResult<FileInfo>} 文件上传路径
 */
@PostMapping(value = "")
public ResponseResult<FileInfo> upload(MultipartFile multipartFile) {
    String fileName = multipartFile.getOriginalFilename();
    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
    String newName = UUID.randomUUID() + "." + suffix;

    OSS client = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

    try {
        client.putObject(new PutObjectRequest(BUCKET_NAME, newName, new ByteArrayInputStream(multipartFile.getBytes())));
        // 上传文件路径 = http://BUCKET_NAME.ENDPOINT/自定义路径/fileName
        return new ResponseResult<FileInfo>(ResponseResult.CodeStatus.OK, "文件上传成功", new FileInfo("http://" + BUCKET_NAME + "." + ENDPOINT + "/" + newName));
    } catch (IOException e) {
        return new ResponseResult<FileInfo>(ResponseResult.CodeStatus.FAIL, "文件上传失败,请重试");
    } finally {
        client.shutdown();
    }
}
 
Example #2
Source File: AliyunStorage.java    From litemall with MIT License 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
    try {
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);
        // 对象键(Key)是对象在存储桶中的唯一标识。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }

}
 
Example #3
Source File: AliyunStorage.java    From mall with MIT License 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
    try {
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);
        // 对象键(Key)是对象在存储桶中的唯一标识。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}
 
Example #4
Source File: ALiYunOSSUploadFileTemplateServiceImpl.java    From plumemo with Apache License 2.0 6 votes vote down vote up
@Override
public String doSaveFileStore(final MultipartFile file) {
    final OSS ossClient = new OSSClientBuilder()
            .build(ConfigCache.getConfig(Constants.ALIYUN_OSS_ENDPOINT),
                    ConfigCache.getConfig(Constants.ALIYUN_OSS_ACCESS_KEY),
                    ConfigCache.getConfig(Constants.ALIYUN_OSS_SECRET_KEY));
    try {
        final String fileName = FileUtil.createSingleFilePath(ConfigCache.getConfig(Constants.ALIYUN_OSS_PATH), file.getOriginalFilename());
        final PutObjectRequest putObjectRequest = new PutObjectRequest(ConfigCache.getConfig(Constants.ALIYUN_OSS_BUCKET), fileName, file.getInputStream());
        final ObjectMetadata metadata = new ObjectMetadata();
        metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
        putObjectRequest.setMetadata(metadata);
        ossClient.putObject(putObjectRequest);
        return ConfigCache.getConfig(Constants.ALIYUN_OSS_IMAGE_DOMAIN) + fileName;
    } catch (final IOException e) {
        return "";
    } finally {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }
}
 
Example #5
Source File: OSSInterface.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * 上传图片
 *
 * @param fileName    文件名
 * @param inputStream 流
 */
public String uploadImageToOSS(String fileName, InputStream inputStream) {
    /**
     * 创建OSS客户端
     */
    try {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String[] names = fileName.split("[.]");
        String name = uuid + "." + names[names.length - 1];
        ossClient.putObject(new PutObjectRequest(bucketName_user, folder + name, inputStream));
        return key + folder + name;
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
    } finally {
        ossClient.shutdown();
    }
    return null;
}
 
Example #6
Source File: OSSInterface.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
public static String uploadImage(String fileName, InputStream inputStream, String bucketName) {
    try {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String[] names = fileName.split("[.]");
        String name = uuid + "." + names[names.length - 1];
        OSSFather.getOSSClient().putObject(new PutObjectRequest(bucketName, folder.substring(1) + name, inputStream));
        return key + folder + name ;// last;
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getMessage());
    } finally {
        ossClient.shutdown();
    }
    return null;

}
 
Example #7
Source File: SimpleOssUpload.java    From tools with MIT License 6 votes vote down vote up
@Override
public String upload(MultipartFile file, String dir, String bucket) {
    this.createBucket(bucket);
    if (file.getOriginalFilename() == null) {
        throw new NullPointerException("The file name cannot be empty");
    }
    if (!"".equals(dir)) {
        dir = dir + "/";
    }
    String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    String fileName = String.format("%s%s", dir + UUID.randomUUID().toString().replaceAll("-", ""), extension);
    try {
        this.ossClient.putObject(new PutObjectRequest(this.ossMeta.getBucket(), fileName, file.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileName;
}
 
Example #8
Source File: AliyunStorage.java    From dts-shop with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
	try {
		logger.info("阿里云存储OSS对象 内容长度:{},文件类型:{},KeyName:{}",contentLength,contentType,keyName);
		// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentLength(contentLength);
		objectMetadata.setContentType(contentType);
		
		// 对象键(Key)是对象在存储桶中的唯一标识。
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
		
		PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
		if (putObjectResult != null && putObjectResult.getResponse() != null) {
			logger.info("阿里云存储结果code:" + putObjectResult.getResponse().getStatusCode());
		}
	} catch (Exception ex) {
		logger.error("阿里云存储 keyName:{} ,失败:{}",keyName,ex.getMessage());
		ex.printStackTrace();
	}

}
 
Example #9
Source File: AliyunStorage.java    From BigDataPlatform with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 阿里云OSS对象存储简单上传实现
 */
@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
    try {
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);
        // 对象键(Key)是对象在存储桶中的唯一标识。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        PutObjectResult putObjectResult = getOSSClient().putObject(putObjectRequest);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }

}
 
Example #10
Source File: AliyunStorageBizServiceImpl.java    From unimall with Apache License 2.0 5 votes vote down vote up
@Override
public String upload(String fileName, InputStream is, long contentLength, String contentType) {
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentLength(contentLength);
    objectMetadata.setContentType(contentType);
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, is, objectMetadata);
    ossClient.putObject(putObjectRequest);
    return baseUrl + fileName;
}
 
Example #11
Source File: UploadCloudTests.java    From MyShopPlus with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpload() {
    // 创建一个访问 OSS 的实例
    OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    try {
        // 文件上传
        System.out.println("Uploading a new object to OSS from an input stream\n");
        String content = "Thank you for using Aliyun Object Storage Service";
        client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));

        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

        // 文件下载
        System.out.println("Downloading an object");
        OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());
    } 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());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.shutdown();
    }
}
 
Example #12
Source File: AliOSSBlobStore.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Override
public String putBlob(String container, Blob blob) {
    return doOssOperation(oss -> {
        try {
            ObjectMetadata objectMetadata = createObjectMetadataFromBlob(blob);
            PutObjectRequest request = new PutObjectRequest(container, blob.getMetadata()
                                                                           .getProviderId(), blob.getPayload()
                                                                                                 .openStream(), objectMetadata);
            PutObjectResult result = oss.putObject(request);
            return result.getETag();
        } catch (IOException e) {
            throw new SLException(e);
        }
    });
}
 
Example #13
Source File: AliOSSBlobStoreTest.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutBlob() {
    Mockito.when(ossClient.putObject(any())).thenReturn(new PutObjectResult());
    Blob blob = new BlobBuilderImpl().name(FILENAME)
                                     .payload(PAYLOAD)
                                     .userMetadata(getUserMetadata())
                                     .build();
    aliOSSBlobStore.putBlob(CONTAINER, blob);
    Mockito.verify(ossClient)
           .putObject(any(PutObjectRequest.class));
}
 
Example #14
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public ObjectOperation store(File file, ObjectMetadata meta, Consumer<PutObjectResult> onCompleted){
	if(!file.exists()){
		throw new BaseException("file is not exists!");
	}
	PutObjectResult result = putObject(new PutObjectRequest(bucketName, key, file, meta));
	if (onCompleted!=null) {
		onCompleted.accept(result);
	} else {
		if (!result.getResponse().isSuccessful()) {
			throw new BaseException("uplaod to oss error: " + result.getResponse().getErrorResponseAsString());
		}
	}
	return this;
}
 
Example #15
Source File: OSSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void save(Note note, AuthenticationInfo subject) throws IOException {
  String content = note.toJson();
  PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
          rootFolder + "/" + buildNoteFileName(note.getId(), note.getPath()),
          new ByteArrayInputStream(content.getBytes()));
  ossClient.putObject(putObjectRequest);
}
 
Example #16
Source File: OssConcurrentGetObjectTests.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
	/*
	 * Constructs a client instance with your account for accessing OSS
	 */
	client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

	try {
		/*
		 * Upload an object to your bucket
		 */
		System.out.println("Uploading a new object to OSS from a file\n");
		client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

		/*
		 * Get size of the object and pre-create a random access file to
		 * hold object data
		 */
		ObjectMetadata metadata = client.getObjectMetadata(bucketName, key);
		long objectSize = metadata.getContentLength();
		RandomAccessFile raf = new RandomAccessFile(localFilePath, "rw");
		raf.setLength(objectSize);
		raf.close();

		/*
		 * Calculate how many blocks to be divided
		 */
		final long blockSize = 1 * 1024 * 1024L; // 1MB
		int blockCount = (int) (objectSize / blockSize);
		if (objectSize % blockSize != 0) {
			blockCount++;
		}
		System.out.println("Total blocks count " + blockCount + "\n");

		/*
		 * Download the object concurrently
		 */
		System.out.println("Start to download " + key + "\n");
		for (int i = 0; i < blockCount; i++) {
			long startPos = i * blockSize;
			long endPos = (i + 1 == blockCount) ? objectSize : (i + 1) * blockSize;
			executorService.execute(new BlockFetcher(startPos, endPos, i + 1));
		}

		/*
		 * Waiting for all blocks finished
		 */
		executorService.shutdown();
		while (!executorService.isTerminated()) {
			try {
				executorService.awaitTermination(5, TimeUnit.SECONDS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		/*
		 * Verify whether all blocks are finished
		 */
		if (completedBlocks.intValue() != blockCount) {
			throw new IllegalStateException("Download fails due to some blocks are not finished yet");
		} else {
			System.out.println("Succeed to download object " + 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.getErrorMessage());
		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.
		 */
		if (client != null) {
			client.shutdown();
		}
	}
}
 
Example #17
Source File: OssSimpleGetObjectTests.java    From super-cloudops with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
	/*
	 * Constructs a client instance with your account for accessing OSS
	 */
	OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

	try {

		/**
		 * Note that there are two ways of uploading an object to your
		 * bucket, the one by specifying an input stream as content source,
		 * the other by specifying a file.
		 */

		/*
		 * Upload an object to your bucket from an input stream
		 */
		System.out.println("Uploading a new object to OSS from an input stream\n");
		String content = "Thank you for using Aliyun Object Storage Service";
		client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));

		/*
		 * Upload an object to your bucket from a file
		 */
		System.out.println("Uploading a new object to OSS from a file\n");
		client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));

		/*
		 * Download an object from your bucket
		 */
		System.out.println("Downloading an object");
		OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
		System.out.println("ObjectKey: " + object.getKey());
		System.out.println("ClientCRC: " + object.getClientCRC());
		System.out.println("ServerCRC: " + object.getServerCRC());
		System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
		displayTextInputStream(object.getObjectContent());

	} 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.getErrorMessage());
		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();
	}
}
 
Example #18
Source File: SimpleGetObjectSample.java    From albert with MIT License 4 votes vote down vote up
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 {
        
        /**
         * Note that there are two ways of uploading an object to your bucket, the one 
         * by specifying an input stream as content source, the other by specifying a file.
         */
        
        /*
         * Upload an object to your bucket from an input stream
         */
        System.out.println("Uploading a new object to OSS from an input stream\n");
        String content = "Thank you for using Aliyun Object Storage Service";
        client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));
        
        /*
         * Upload an object to your bucket from a file
         */
        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
        
        /*
         * Download an object from your bucket
         */
        System.out.println("Downloading an object");
        OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: "  + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());
        
    } 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();
    }
}
 
Example #19
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public PutObjectResult putObject(PutObjectRequest request){
	return ossClient.putObject(request);
}
 
Example #20
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public ObjectOperation store(InputStream inputStream, ObjectMetadata meta){
	Assert.notNull(inputStream, "inputStream can not be null");
	putObject(new PutObjectRequest(bucketName, key, inputStream, meta));
	return this;
}
 
Example #21
Source File: OssClientWrapper.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public PutObjectResult putObject(PutObjectRequest request){
	PutObjectResult result = wrapper.putObject(request);
	return result;
}