springboot对象存储亚马逊aws集成(s3协议)

文章介绍了如何在Java项目中使用AWSJavaSDK操作AmazonS3,包括上传文件、处理依赖和文件名,以及下载文件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. POM文件

 <!-- AmazonS3对象存储 -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.76</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-core</artifactId>
            <version>1.11.779</version>
        </dependency>

上传upload

/**
     * 收集并上传至S3服务器
     * 返回ID
     * @param identify
     * @param fileInput
     * @return
     */
    public OperationResult upload(@RequestParam(required=false) String identify, @RequestParam("fileInput") MultipartFile fileInput)
    {
        if (Objects.isNull(fileInput)) {
            String errorMsg = "fileInput参数为空";
            logger.error(errorMsg);
            return OperationResult.buildFailureResult(errorMsg);
        }
        String fileName = fileInput.getOriginalFilename();
        logger.error("-----fileName-----"+fileName);
        if (StringUtils.isBlank(fileName)) {
            String errorMsg = "文件名称为空";
            logger.error(errorMsg);
            return OperationResult.buildFailureResult(errorMsg);
        }
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1);
        String realName = String.format("%s.%s", new Object[] { IDUtil.createUUID(), ext });
        try { InputStream in = fileInput.getInputStream(); Throwable localThrowable3 = null;
            try { identify = org.springframework.util.StringUtils.cleanPath(identify);
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(fileInput.getSize());
                Map map = new HashMap(1);
                map.put("fileName", URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString()));
                objectMetadata.setUserMetadata(map);
                this.upload(identify, in, objectMetadata);
                Map resultMap = new HashMap(1);
//                resultMap.put("identify", identify);
                logger.error("-----fileId-----"+identify);
                OperationResult localOperationResult = OperationResult.buildSuccessResult("对象存储上传文件成功", resultMap);
                return localOperationResult;
            }
            catch (Throwable localThrowable1)
            {
                localThrowable3 = localThrowable1; throw localThrowable1;
            }
            finally
            {
                if (in != null) if (localThrowable3 != null) try { in.close(); } catch (Throwable localThrowable2) { localThrowable3.addSuppressed(localThrowable2); } else in.close();
            }
        } catch (Exception e) {
            String errorMsg = "对象存储上传文件失败";
            logger.error(errorMsg, e);
            return OperationResult.buildFailureResult("对象存储上传文件失败");
        }
    }

下载download

 /**
     * 文件下载
     * @param request
     * @param
     * @param
     * @return
     */
    public Object fileDownloadByFileId(HttpServletRequest request, HttpServletResponse response,String storeId  , String orgfileName) throws Exception {
       ResponseEntity entity=null;
        if(StringUtils.isEmpty(storeId)){
            throw new Exception("请上传文件信息");
        }
        if(StringUtils.isEmpty(orgfileName)){
            throw new Exception("请上传文件名信息");
        }
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(); Throwable localThrowable6 = null;
            try { InputStream in =  download(storeId); Throwable localThrowable7 = null;
                try { ObjectMetadata objectMetadata = getObjectMetadata(storeId);
                    long contentLength = objectMetadata.getContentLength();
                    String fileName =orgfileName==null? URLDecoder.decode(objectMetadata.getUserMetaDataOf("fileName"), StandardCharsets.UTF_8.toString()):orgfileName;
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    headers.add("Accept-Ranges", "bytes");
                    headers.add("Content-Length", Long.toString(contentLength));
                    headers.add("Content-Disposition", "attachment; filename='" + fileName + "'; filename*=utf-8''" + fileName);
                    IOUtils.copy(in, bos);
                    entity = new ResponseEntity(bos.toByteArray(), headers,  HttpStatus.OK);
                } catch (Throwable localThrowable1)                {
                    localThrowable7 = localThrowable1; throw localThrowable1;
                } finally{
                    if (in != null) if (localThrowable7 != null) try { in.close(); } catch (Throwable localThrowable2) { localThrowable7.addSuppressed(localThrowable2); } else in.close();
                }
            }catch (Throwable localThrowable4){
                localThrowable6 = localThrowable4; throw localThrowable4;
            }finally{
                if (bos != null) if (localThrowable6 != null) try { bos.close(); } catch (Throwable localThrowable5) { localThrowable6.addSuppressed(localThrowable5); } else bos.close();
            }
        }catch (AmazonS3Exception e){
            String errorMsg = "对象存储连接失败或者identify对应的文件不存在";
            logger.error(errorMsg, e);
            return OperationResult.buildFailureResult(errorMsg);
        }catch (Exception e) {
            String errorMsg = "对象存储下载文件失败";
            logger.error(errorMsg, e);
            return OperationResult.buildFailureResult(errorMsg, e.getMessage());
        }
        return entity;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值