Java Code Examples for com.aliyun.oss.OSS#shutdown()
The following examples show how to use
com.aliyun.oss.OSS#shutdown() .
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: OSSUtil.java From seed with Apache License 2.0 | 6 votes |
/** * 文件上传 * @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 2
Source File: OSSUtil.java From seed with Apache License 2.0 | 6 votes |
/** * 获取文件的临时地址(供文件预览使用) * 图片处理:https://help.aliyun.com/document_detail/47505.html * 异常码描:https://help.aliyun.com/document_detail/32023.html * @param bucket 必传:存储空间名称 * @param endpoint 必传:存储空间所属地域的访问域名 * @param isImg 必传:获取的文件是否为图片 * @param process 选传:(isImg=true时必传)图片的x-oss-process参数值(传空则返回原图),举例:image/resize,p_50表示将图按比例缩略到原来的1/2 * @param timeout 必传:有效时长,单位:分钟 * @return 返回文件的完整地址(浏览器可直接访问) * Comment by 玄玉<https://jadyer.cn/> on 2018/4/9 17:23. */ public static String getFileURL(String endpoint, String accessKeyId, String accessKeySecret, String bucket, String key, boolean isImg, String process, int timeout) { LogUtil.getLogger().info("获取文件临时URL,请求ossKey=[{}],process=[{}], timeout=[{}]min", key, process, timeout); OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key, HttpMethod.GET); req.setExpiration(DateUtils.addMinutes(new Date(), timeout)); if(isImg){ req.setProcess(StringUtils.isNotBlank(process) ? process : "image/resize,p_100"); } String imgURL = ossClient.generatePresignedUrl(req).toString(); imgURL = imgURL.startsWith("http://") ? imgURL.replace("http://", "https://") : imgURL; LogUtil.getLogger().info("获取文件临时URL,请求ossKey=[{}],应答fileUrl=[{}]", key, imgURL); return imgURL; } catch (OSSException oe) { throw new SeedException("获取文件临时URL,OSS服务端异常,RequestID="+oe.getRequestId() + ",HostID="+oe.getHostId() + ",Code="+oe.getErrorCode() + ",Message="+oe.getMessage()); } catch (ClientException ce) { throw new SeedException("获取文件临时URL,OSS客户端异常,RequestID="+ce.getRequestId() + ",Code="+ce.getErrorCode() + ",Message="+ce.getMessage()); } catch (Throwable e) { throw new SeedException("获取文件临时URL,OSS未知异常:" + e.getMessage()); } finally { if(null != ossClient){ ossClient.shutdown(); } } }
Example 3
Source File: ALiYunOSSUploadFileTemplateServiceImpl.java From plumemo with Apache License 2.0 | 6 votes |
@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: UploadController.java From MyShopPlus with Apache License 2.0 | 6 votes |
/** * 文件上传 * * @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 5
Source File: OssUploadSample.java From super-cloudops with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException { OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key); // The local file to upload---it must exist. uploadFileRequest.setUploadFile(uploadFile); // Sets the concurrent upload task number to 5. uploadFileRequest.setTaskNum(5); // Sets the part size to 1MB. uploadFileRequest.setPartSize(1024 * 1024 * 1); // Enables the checkpoint file. By default it's off. uploadFileRequest.setEnableCheckpoint(true); UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest); CompleteMultipartUploadResult multipartUploadResult = uploadResult.getMultipartUploadResult(); System.out.println(multipartUploadResult.getETag()); } 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()); } catch (Throwable e) { e.printStackTrace(); } finally { ossClient.shutdown(); } }
Example 6
Source File: OSSUtil.java From seed with Apache License 2.0 | 5 votes |
/** * 文件下载 * @param bucket 存储空间名称 * @param endpoint 存储空间所属地域的访问域名 * @param localURL 保存在本地的包含完整路径和后缀的完整文件名,若传空则默认放到Java临时目录中 * @return localURL(若文件不存在则返回OSSUtil.NO_FILE) * Comment by 玄玉<https://jadyer.cn/> on 2018/4/9 17:24. */ public static String download(String bucket, String endpoint, String key, String accessKeyId, String accessKeySecret, String localURL) { if(StringUtils.isBlank(localURL)){ //若未传localURL,则把下载到的文件放到Java临时目录 localURL = System.getProperty("java.io.tmpdir") + "/ossutil-download/" + key; ////若文件名称不含后缀,那就主动添加后缀 //if("".equals(FilenameUtils.getExtension(key))){ // localURL += ".txt"; //} } OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { if(!ossClient.doesObjectExist(bucket, key)){ return OSSUtil.NO_FILE; } //ossClient.getObject(new GetObjectRequest(bucket, key), new File(localURL)); InputStream is = ossClient.getObject(bucket, key).getObjectContent(); FileUtils.copyInputStreamToFile(is, new File(localURL)); return localURL; } 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 { if(null != ossClient){ ossClient.shutdown(); } } }
Example 7
Source File: AliOSSBlobStore.java From multiapps-controller with Apache License 2.0 | 5 votes |
private <R> R doOssOperation(Function<OSS, R> function, boolean shutdownClient) { OSS ossClient = aliOSSApi.getOSSClient(); R result = function.apply(ossClient); if (shutdownClient) { ossClient.shutdown(); } return result; }
Example 8
Source File: AliOssAutoConfigure.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
@Override protected void delete(List<FileDeleteDO> list, FileDeleteDO file) { FileServerProperties.Ali ali = fileProperties.getAli(); String bucketName = ali.getBucketName(); OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(), ali.getAccessKeySecret()); ossClient.deleteObject(bucketName, file.getRelativePath() + StrPool.SLASH + file.getFileName()); ossClient.shutdown(); }
Example 9
Source File: AliOssAutoConfigure.java From zuihou-admin-cloud with Apache License 2.0 | 5 votes |
@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 10
Source File: OssDownloadTests.java From super-cloudops with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException { OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, key); // Sets the local file to download to downloadFileRequest.setDownloadFile(downloadFile); // Sets the concurrent task thread count 5. By default it's 1. downloadFileRequest.setTaskNum(5); // Sets the part size, by default it's 100K. downloadFileRequest.setPartSize(1024 * 1024 * 1); // Enable checkpoint. By default it's false. downloadFileRequest.setEnableCheckpoint(true); DownloadFileResult downloadResult = ossClient.downloadFile(downloadFileRequest); ObjectMetadata objectMetadata = downloadResult.getObjectMetadata(); System.out.println(objectMetadata.getETag()); System.out.println(objectMetadata.getLastModified()); System.out.println(objectMetadata.getUserMetadata().get("meta")); } 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()); } catch (Throwable e) { e.printStackTrace(); } finally { ossClient.shutdown(); } }
Example 11
Source File: AliOssAutoConfigure.java From zuihou-admin-boot with Apache License 2.0 | 5 votes |
@Override protected void delete(List<FileDeleteDO> list, FileDeleteDO file) { FileServerProperties.Ali ali = fileProperties.getAli(); String bucketName = ali.getBucketName(); OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(), ali.getAccessKeySecret()); ossClient.deleteObject(bucketName, file.getRelativePath() + StrPool.SLASH + file.getFileName()); ossClient.shutdown(); }
Example 12
Source File: AliOssAutoConfigure.java From zuihou-admin-boot with Apache License 2.0 | 5 votes |
@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 13
Source File: UploadCloudTests.java From MyShopPlus with Apache License 2.0 | 5 votes |
@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 14
Source File: OssSimpleGetObjectTests.java From super-cloudops with Apache License 2.0 | 4 votes |
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 15
Source File: FileManager.java From signature with MIT License | 4 votes |
/** * create by: iizvv * description: 上传文件 * create time: 2019-07-24 10:27 * @return */ public void uploadFile(File file, String objName, Boolean isTemp) { String bucket = isTemp==true?Config.aliTempBucket:Config.aliMainBucket; OSS ossClient = new OSSClientBuilder().build(Config.vpcEndpoint, Config.accessKeyID, Config.accessKeySecret); InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucket, objName); InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request); String uploadId = result.getUploadId(); List<PartETag> partETags = new ArrayList<PartETag>(); final long partSize = 4 * 1024 * 1024L; long fileLength = file.length(); int partCount = (int) (fileLength / partSize); if (fileLength % partSize != 0) { partCount++; } for (int i = 0; i < partCount; i++) { long startPos = i * partSize; long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize; InputStream instream = null; try { instream = new FileInputStream(file); // 跳过已经上传的分片。 instream.skip(startPos); UploadPartRequest uploadPartRequest = new UploadPartRequest(); uploadPartRequest.setBucketName(bucket); uploadPartRequest.setKey(objName); uploadPartRequest.setUploadId(uploadId); uploadPartRequest.setInputStream(instream); // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100KB。 uploadPartRequest.setPartSize(curPartSize); // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出这个范围,OSS将返回InvalidArgument的错误码。 uploadPartRequest.setPartNumber( i + 1); // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。 UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest); // 每次上传分片之后,OSS的返回结果会包含一个PartETag。PartETag将被保存到partETags中。 partETags.add(uploadPartResult.getPartETag()); } catch (IOException e) { e.printStackTrace(); } } Collections.sort(partETags, new Comparator<PartETag>() { public int compare(PartETag p1, PartETag p2) { return p1.getPartNumber() - p2.getPartNumber(); } }); CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucket, objName, uploadId, partETags); ossClient.completeMultipartUpload(completeMultipartUploadRequest); ossClient.shutdown(); }
Example 16
Source File: AliOssAutoConfigure.java From zuihou-admin-boot with Apache License 2.0 | 4 votes |
@Override protected R<File> merge(List<java.io.File> files, String path, String fileName, FileChunksMergeDTO info) throws IOException { FileServerProperties.Ali ali = fileProperties.getAli(); String bucketName = ali.getBucketName(); OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(), ali.getAccessKeySecret()); //日期文件夹 String relativePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM")); // web服务器存放的绝对路径 String relativeFileName = relativePath + StrPool.SLASH + fileName; ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentDisposition("attachment;fileName=" + info.getSubmittedFileName()); metadata.setContentType(info.getContextType()); //步骤1:初始化一个分片上传事件。 InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, relativeFileName, metadata); InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request); // 返回uploadId,它是分片上传事件的唯一标识,您可以根据这个ID来发起相关的操作,如取消分片上传、查询分片上传等。 String uploadId = result.getUploadId(); // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。 List<PartETag> partETags = new ArrayList<PartETag>(); for (int i = 0; i < files.size(); i++) { java.io.File file = files.get(i); FileInputStream in = FileUtils.openInputStream(file); UploadPartRequest uploadPartRequest = new UploadPartRequest(); uploadPartRequest.setBucketName(bucketName); uploadPartRequest.setKey(relativeFileName); uploadPartRequest.setUploadId(uploadId); uploadPartRequest.setInputStream(in); // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100KB。 uploadPartRequest.setPartSize(file.length()); // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出这个范围,OSS将返回InvalidArgument的错误码。 uploadPartRequest.setPartNumber(i + 1); // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。 UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest); // 每次上传分片之后,OSS的返回结果会包含一个PartETag。PartETag将被保存到partETags中。 partETags.add(uploadPartResult.getPartETag()); } /* 步骤3:完成分片上传。 */ // 排序。partETags必须按分片号升序排列。 partETags.sort(Comparator.comparingInt(PartETag::getPartNumber)); // 在执行该操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。 CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, relativeFileName, uploadId, partETags); CompleteMultipartUploadResult uploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest); String url = new StringBuilder(ali.getUriPrefix()) .append(relativePath) .append(StrPool.SLASH) .append(fileName) .toString(); File filePo = File.builder() .relativePath(relativePath) .group(uploadResult.getETag()) .path(uploadResult.getRequestId()) .url(StringUtils.replace(url, "\\\\", StrPool.SLASH)) .build(); // 关闭OSSClient。 ossClient.shutdown(); return R.success(filePo); }
Example 17
Source File: AliOssAutoConfigure.java From zuihou-admin-cloud with Apache License 2.0 | 4 votes |
@Override protected void copyFile(File file) { FileServerProperties.Ali ali = fileProperties.getAli(); String sourceBucketName = ali.getBucketName(); String destinationBucketName = ali.getBucketName(); OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(), ali.getAccessKeySecret()); String sourceObjectName = file.getRelativePath() + StrPool.SLASH + file.getFilename(); String fileName = UUID.randomUUID().toString() + StrPool.DOT + file.getExt(); String destinationObjectName = file.getRelativePath() + StrPool.SLASH + fileName; ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceObjectName); // 获取被拷贝文件的大小。 // 获取被拷贝文件的大小。 long contentLength = objectMetadata.getContentLength(); // 设置分片大小为10MB。 long partSize = 1024 * 1024 * 10; // 计算分片总数。 int partCount = (int) (contentLength / partSize); if (contentLength % partSize != 0) { partCount++; } log.info("total part count:{}", partCount); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentDisposition("attachment;fileName=" + file.getSubmittedFileName()); metadata.setContentType(file.getContextType()); // 初始化拷贝任务。可以通过InitiateMultipartUploadRequest指定目标文件元信息。 InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(destinationBucketName, destinationObjectName, metadata); InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest); String uploadId = initiateMultipartUploadResult.getUploadId(); // 分片拷贝。 List<PartETag> partETags = new ArrayList<>(); for (int i = 0; i < partCount; i++) { // 计算每个分片的大小。 long skipBytes = partSize * i; long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes; // 创建UploadPartCopyRequest。可以通过UploadPartCopyRequest指定限定条件。 UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName); uploadPartCopyRequest.setUploadId(uploadId); uploadPartCopyRequest.setPartSize(size); uploadPartCopyRequest.setBeginIndex(skipBytes); uploadPartCopyRequest.setPartNumber(i + 1); UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest); // 将返回的分片ETag保存到partETags中。 partETags.add(uploadPartCopyResult.getPartETag()); } // 提交分片拷贝任务。 CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest( destinationBucketName, destinationObjectName, uploadId, partETags); ossClient.completeMultipartUpload(completeMultipartUploadRequest); String url = new StringBuilder(ali.getUriPrefix()) .append(file.getRelativePath()) .append(StrPool.SLASH) .append(fileName) .toString(); file.setUrl(StringUtils.replace(url, "\\\\", StrPool.SLASH)); file.setFilename(fileName); // 关闭OSSClient。 ossClient.shutdown(); }
Example 18
Source File: AliOssAutoConfigure.java From zuihou-admin-cloud with Apache License 2.0 | 4 votes |
@Override protected R<File> merge(List<java.io.File> files, String path, String fileName, FileChunksMergeDTO info) throws IOException { FileServerProperties.Ali ali = fileProperties.getAli(); String bucketName = ali.getBucketName(); OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(), ali.getAccessKeySecret()); //日期文件夹 String relativePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM")); // web服务器存放的绝对路径 String relativeFileName = relativePath + StrPool.SLASH + fileName; ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentDisposition("attachment;fileName=" + info.getSubmittedFileName()); metadata.setContentType(info.getContextType()); //步骤1:初始化一个分片上传事件。 InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, relativeFileName, metadata); InitiateMultipartUploadResult result = ossClient.initiateMultipartUpload(request); // 返回uploadId,它是分片上传事件的唯一标识,您可以根据这个ID来发起相关的操作,如取消分片上传、查询分片上传等。 String uploadId = result.getUploadId(); // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成。 List<PartETag> partETags = new ArrayList<PartETag>(); for (int i = 0; i < files.size(); i++) { java.io.File file = files.get(i); FileInputStream in = FileUtils.openInputStream(file); UploadPartRequest uploadPartRequest = new UploadPartRequest(); uploadPartRequest.setBucketName(bucketName); uploadPartRequest.setKey(relativeFileName); uploadPartRequest.setUploadId(uploadId); uploadPartRequest.setInputStream(in); // 设置分片大小。除了最后一个分片没有大小限制,其他的分片最小为100KB。 uploadPartRequest.setPartSize(file.length()); // 设置分片号。每一个上传的分片都有一个分片号,取值范围是1~10000,如果超出这个范围,OSS将返回InvalidArgument的错误码。 uploadPartRequest.setPartNumber(i + 1); // 每个分片不需要按顺序上传,甚至可以在不同客户端上传,OSS会按照分片号排序组成完整的文件。 UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest); // 每次上传分片之后,OSS的返回结果会包含一个PartETag。PartETag将被保存到partETags中。 partETags.add(uploadPartResult.getPartETag()); } /* 步骤3:完成分片上传。 */ // 排序。partETags必须按分片号升序排列。 partETags.sort(Comparator.comparingInt(PartETag::getPartNumber)); // 在执行该操作时,需要提供所有有效的partETags。OSS收到提交的partETags后,会逐一验证每个分片的有效性。当所有的数据分片验证通过后,OSS将把这些分片组合成一个完整的文件。 CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, relativeFileName, uploadId, partETags); CompleteMultipartUploadResult uploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest); String url = new StringBuilder(ali.getUriPrefix()) .append(relativePath) .append(StrPool.SLASH) .append(fileName) .toString(); File filePo = File.builder() .relativePath(relativePath) .group(uploadResult.getETag()) .path(uploadResult.getRequestId()) .url(StringUtils.replace(url, "\\\\", StrPool.SLASH)) .build(); // 关闭OSSClient。 ossClient.shutdown(); return R.success(filePo); }
Example 19
Source File: AliOssAutoConfigure.java From zuihou-admin-boot with Apache License 2.0 | 4 votes |
@Override protected void copyFile(File file) { FileServerProperties.Ali ali = fileProperties.getAli(); String sourceBucketName = ali.getBucketName(); String destinationBucketName = ali.getBucketName(); OSS ossClient = new OSSClientBuilder().build(ali.getEndpoint(), ali.getAccessKeyId(), ali.getAccessKeySecret()); String sourceObjectName = file.getRelativePath() + StrPool.SLASH + file.getFilename(); String fileName = UUID.randomUUID().toString() + StrPool.DOT + file.getExt(); String destinationObjectName = file.getRelativePath() + StrPool.SLASH + fileName; ObjectMetadata objectMetadata = ossClient.getObjectMetadata(sourceBucketName, sourceObjectName); // 获取被拷贝文件的大小。 // 获取被拷贝文件的大小。 long contentLength = objectMetadata.getContentLength(); // 设置分片大小为10MB。 long partSize = 1024 * 1024 * 10; // 计算分片总数。 int partCount = (int) (contentLength / partSize); if (contentLength % partSize != 0) { partCount++; } log.info("total part count:{}", partCount); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentDisposition("attachment;fileName=" + file.getSubmittedFileName()); metadata.setContentType(file.getContextType()); // 初始化拷贝任务。可以通过InitiateMultipartUploadRequest指定目标文件元信息。 InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(destinationBucketName, destinationObjectName, metadata); InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient.initiateMultipartUpload(initiateMultipartUploadRequest); String uploadId = initiateMultipartUploadResult.getUploadId(); // 分片拷贝。 List<PartETag> partETags = new ArrayList<>(); for (int i = 0; i < partCount; i++) { // 计算每个分片的大小。 long skipBytes = partSize * i; long size = partSize < contentLength - skipBytes ? partSize : contentLength - skipBytes; // 创建UploadPartCopyRequest。可以通过UploadPartCopyRequest指定限定条件。 UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucketName, sourceObjectName, destinationBucketName, destinationObjectName); uploadPartCopyRequest.setUploadId(uploadId); uploadPartCopyRequest.setPartSize(size); uploadPartCopyRequest.setBeginIndex(skipBytes); uploadPartCopyRequest.setPartNumber(i + 1); UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest); // 将返回的分片ETag保存到partETags中。 partETags.add(uploadPartCopyResult.getPartETag()); } // 提交分片拷贝任务。 CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest( destinationBucketName, destinationObjectName, uploadId, partETags); ossClient.completeMultipartUpload(completeMultipartUploadRequest); String url = new StringBuilder(ali.getUriPrefix()) .append(file.getRelativePath()) .append(StrPool.SLASH) .append(fileName) .toString(); file.setUrl(StringUtils.replace(url, "\\\\", StrPool.SLASH)); file.setFilename(fileName); // 关闭OSSClient。 ossClient.shutdown(); }
Example 20
Source File: FileManager.java From signature with MIT License | 3 votes |
/** * 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(); }