接入京东云OSS,实现文件的上传预下载

一、京东云OSS文档链接

https://docs.jdcloud.com/cn/object-storage-service/sign-up-service-2

二、配置POM文件

            <dependency>
                <groupId>com.amazonaws</groupId>
                <artifactId>aws-java-sdk-s3</artifactId>
                <version>1.11.490</version>
            </dependency>

三、进行配置

通过自定义一个OSSConfig配置类生成一个访问OSS的Client(AmazonS3 ),并注入到spring的容器中

@Configuration
public class OSSConfig {

    @Value("${oss.access-key}")
    private String accessKey;

    @Value("${oss.secret-key}")
    private String secretKey;

    @Value("${oss.endpoint}")
    private String endpoint;

    @Value("${oss.region}")
    private String region;

    @Bean
    public AmazonS3 amazonS3() {
        ClientConfiguration config = new ClientConfiguration();
        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(endpoint, region);
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey,secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

        AmazonS3 s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .build();
        return s3;
    }
}

  • accessKey和secretKey
    • 要接入京东云OSS,需要拥有一对有效的Access Key(包括AccessKeyId和AccessKeySecretID)进行签名认证。可以通过如下步骤获得:

      • 注册京东云账号

      • 申请AccessKey

  • endpoint和region可参考:https://docs.jdcloud.com/cn/object-storage-service/oss-endpont-list

使用

@Service
@Slf4j
public class OssServiceImpl implements IOSSService {

    @Resource
    private AmazonS3 amazonS3;

// 你创建的存储空间名
    @Value("${oss.bucket-name}")
    private String budgetName;

/**
* 上传
**/
    @Override
    public String upload(MultipartFile multipartFile) {
        log.info("multipartFile.getName = {}", multipartFile.getName());
        log.info("multipartFile.getContentType = {}", multipartFile.getContentType());
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(multipartFile.getContentType());
        objectMetadata.setContentLength(multipartFile.getSize());
        PutObjectResult putObjectResult = null;
        try {
            putObjectResult = amazonS3.putObject(budgetName , multipartFile.getName() , multipartFile.getInputStream(), objectMetadata);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        log.info("putObjectResult = {}", JSONUtil.toJsonStr(putObjectResult));
        return multipartFile.getName();
    }

/**
* 通过fileName文件名和BudgetName存储空间名即可定位到要下载的资源文件
**/
    @Override
    public void downloadWeb(HttpServletResponse response, String fileName) throws UnsupportedEncodingException {
        S3Object object = amazonS3.getObject(budgetName, fileName);
        S3ObjectInputStream ois = object.getObjectContent();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
        response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(object.getObjectMetadata().getContentLength()));
        try {
            FileUtils.writeBytes(ois, response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值