Java Code Examples for com.aliyun.oss.OSS#putObject()

The following examples show how to use com.aliyun.oss.OSS#putObject() . 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: AliyunOssClient.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * Upload string.
 *
 * @param ossClient the ossClient client
 * @param instream  the instream
 * @param fileName  the file name
 * @return the string
 */
public String upload(@NotNull OSS ossClient,
                     @NotNull InputStream instream,
                     @NotNull String fileName) {
    try {
        // 创建上传 Object 的 Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(instream.available());
        objectMetadata.setCacheControl("no-cache");
        objectMetadata.setHeader("Pragma", "no-cache");
        objectMetadata.setContentType(ImageUtils.getImageType(fileName));
        objectMetadata.setContentDisposition("inline;filename=" + fileName);
        ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
        return getUrl(ossClient, filedir, fileName);
    } catch (IOException | OSSException | ClientException e) {
        log.trace("", e);
    }
    return "";
}
 
Example 3
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 4
Source File: OSSUtil.java    From seed with Apache License 2.0 6 votes vote down vote up
/**
 * 文件上传
 * @param bucket   存储空间名称
 * @param endpoint 存储空间所属地域的访问域名
 * @param key      文件完整名称(建议含后缀)
 * @param is       文件流
 * Comment by 玄玉<https://jadyer.cn/> on 2018/4/9 17:24.
 */
public static void upload(String bucket, String endpoint, String key, String accessKeyId, String accessKeySecret, InputStream is) {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        ossClient.putObject(bucket, key, is);
    } catch (OSSException oe) {
        throw new SeedException("文件上传,OSS服务端异常,RequestID="+oe.getRequestId() + ",HostID="+oe.getHostId() + ",Code="+oe.getErrorCode() + ",Message="+oe.getMessage());
    } catch (ClientException ce) {
        throw new SeedException("文件上传,OSS客户端异常,RequestID="+ce.getRequestId() + ",Code="+ce.getErrorCode() + ",Message="+ce.getMessage());
    } catch (Throwable e) {
        throw new SeedException("文件上传,OSS未知异常:" + e.getMessage());
    } finally {
        try {
            if(null != is){
                is.close();
            }
        } catch (final IOException ioe) {
            // ignore
        }
        if(null != ossClient){
            ossClient.shutdown();
        }
    }
}
 
Example 5
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 6
Source File: AliOssAutoConfigure.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
@Override
protected void uploadFile(File file, MultipartFile multipartFile) throws Exception {
    FileServerProperties.Ali ali = fileProperties.getAli();
    OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(),
            ali.getAccessKeySecret());
    String bucketName = ali.getBucketName();
    if (!ossClient.doesBucketExist(bucketName)) {
        ossClient.createBucket(bucketName);
    }

    //生成文件名
    String fileName = StrUtil.join(StrPool.EMPTY, UUID.randomUUID().toString(), StrPool.DOT, file.getExt());
    //日期文件夹
    String tenant = BaseContextHandler.getTenant();
    String relativePath = tenant + StrPool.SLASH + LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH));
    // web服务器存放的绝对路径
    String relativeFileName = relativePath + StrPool.SLASH + fileName;

    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentDisposition("attachment;fileName=" + file.getSubmittedFileName());
    metadata.setContentType(file.getContextType());
    PutObjectRequest request = new PutObjectRequest(bucketName, relativeFileName, multipartFile.getInputStream(), metadata);
    PutObjectResult result = ossClient.putObject(request);

    log.info("result={}", JSONObject.toJSONString(result));

    String url = ali.getUriPrefix() + relativeFileName;
    file.setUrl(StrUtil.replace(url, "\\\\", StrPool.SLASH));
    file.setFilename(fileName);
    file.setRelativePath(relativePath);

    file.setGroup(result.getETag());
    file.setPath(result.getRequestId());

    ossClient.shutdown();
}
 
Example 7
Source File: AliOssAutoConfigure.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@Override
protected void uploadFile(File file, MultipartFile multipartFile) throws Exception {
    FileServerProperties.Ali ali = fileProperties.getAli();
    OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(),
            ali.getAccessKeySecret());
    String bucketName = ali.getBucketName();
    if (!ossClient.doesBucketExist(bucketName)) {
        ossClient.createBucket(bucketName);
    }

    //生成文件名
    String fileName = StrUtil.join(StrPool.EMPTY, UUID.randomUUID().toString(), StrPool.DOT, file.getExt());
    //日期文件夹
    String tenant = BaseContextHandler.getTenant();
    String relativePath = tenant + StrPool.SLASH + LocalDate.now().format(DateTimeFormatter.ofPattern(DEFAULT_MONTH_FORMAT_SLASH));
    // web服务器存放的绝对路径
    String relativeFileName = relativePath + StrPool.SLASH + fileName;

    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentDisposition("attachment;fileName=" + file.getSubmittedFileName());
    metadata.setContentType(file.getContextType());
    PutObjectRequest request = new PutObjectRequest(bucketName, relativeFileName, multipartFile.getInputStream(), metadata);
    PutObjectResult result = ossClient.putObject(request);

    log.info("result={}", JSONObject.toJSONString(result));

    String url = ali.getUriPrefix() + relativeFileName;
    file.setUrl(StrUtil.replace(url, "\\\\", StrPool.SLASH));
    file.setFilename(fileName);
    file.setRelativePath(relativePath);

    file.setGroup(result.getETag());
    file.setPath(result.getRequestId());

    ossClient.shutdown();
}
 
Example 8
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 9
Source File: FileManager.java    From signature with MIT License 3 votes vote down vote up
/**
  * create by: iizvv
  * description: 字节数组方式上传文件
  * create time: 2019-07-24 11:14

  * @return void
  */
public void uploadFile(byte[] bytes, String objName, Boolean isTemp) {
    String bucket = isTemp==true?Config.aliTempBucket:Config.aliMainBucket;
    OSS ossClient = new OSSClientBuilder().build(Config.vpcEndpoint, Config.accessKeyID, Config.accessKeySecret);
    ossClient.putObject(bucket, objName, new ByteArrayInputStream(bytes));
    ossClient.shutdown();
}