springboot文件上传阿里云返回URL

1:引入pom

<!--阿里云对象存储 start-->
		<dependency>
			<groupId>com.aliyun.oss</groupId>
			<artifactId>aliyun-sdk-oss</artifactId>
			<version>2.8.3</version>
		</dependency>
		<!--OSS  end-->

2:在yml文件里配置阿里云OSS信息

  #OSS
oss:
    endpoint: 阿里云控制台获取
    keyid: 阿里云控制台获取
    keysecret: 阿里云控制台获取
    bucketname: 阿里云控制台获取
    filehost: test    #bucket下文件夹的路径

3:创建ConstantProperties来获取yml文件的信息

@Data
@Component
@ConfigurationProperties(prefix = "oss")
public class ConstantProperties {
    private  String endpoint;
    private  String keyid;
    private  String keysecret;
    private  String bucketname;
    private  String filehost;

 		省略set   get 。。。。
}

4:创建文件上传Util

@Service
public class AliyunOSSUtil {
    @Autowired
    private  ConstantProperties constantProperties;
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    /**
     * 上传
     * @param file
     * @return
     */
    public  String upload(File file){
        System.out.println("=========>OSS文件上传开始:"+file.getName());
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        String bucketName=constantProperties.getBucketname();
        String fileHost=constantProperties.getFilehost();
        System.out.println(endpoint+"endpoint");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if(null == file){
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        try {
            //容器不存在,就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = (dateStr + "/" + UUID.randomUUID().toString().replace("-","")+"-"+file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName,CannedAccessControlList.PublicRead);
            if(null != result){
                String url=bucketName+"."+endpoint+"/"+fileUrl;
                //System.out.println("==========>OSS文件上传成功,OSS地址:"+ url);
                return url;
            }
        }catch (OSSException oe){
            oe.getMessage();
        }catch (ClientException ce){
           ce.getMessage();
        }finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 删除
     * @param fileKey
     * @return
     */
    public  String deleteBlog(String fileKey){
        System.out.println("=========>OSS文件删除开始");
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        String bucketName=constantProperties.getBucketname();
        String fileHost=constantProperties.getFilehost();
        try {
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);

            if(!ossClient.doesBucketExist(bucketName)){
                System.out.println("==============>您的Bucket不存在");
                return "您的Bucket不存在";
            }else {
                System.out.println("==============>开始删除Object");
                ossClient.deleteObject(bucketName,fileKey);
                System.out.println("==============>Object删除成功:"+fileKey);
                return "==============>Object删除成功:"+fileKey;
            }
        }catch (Exception ex){
            System.out.println("删除Object失败"+ex);
            return "删除Object失败";
        }
    }

    /**
     * 查询文件名列表
     * @param bucketName
     * @return
     */
    public List<String> getObjectList(String bucketName){
        List<String> listRe = new ArrayList<>();
        String endpoint= constantProperties.getEndpoint();
        String accessKeyId= constantProperties.getKeyid();
        String accessKeySecret=constantProperties.getKeysecret();
        try {
            System.out.println("===========>查询文件名列表");
            OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            //列出11111目录下今天所有文件
            listObjectsRequest.setPrefix("11111/"+format.format(new Date())+"/");
            ObjectListing list = ossClient.listObjects(listObjectsRequest);
            for(OSSObjectSummary objectSummary : list.getObjectSummaries()){
                System.out.println(objectSummary.getKey());
                listRe.add(objectSummary.getKey());
            }
            return listRe;
        }catch (Exception ex){
            System.out.println("==========>查询列表失败"+ex);
            return new ArrayList<>();
        }
    }
}

5:上传到OSS返回URL

   /**
     * 文件上传
     * @param file
     * @return
     */
    public String updateImg(List<MultipartFile> file){
        List list=new ArrayList();
        String str ="";
        try {
            if (null != file) {
                for (int i=0;i<file.size();i++){
                    MultipartFile f=file.get(i);
                    String filename = f.getOriginalFilename();
                    if (!"".equals(filename.trim())) {
                        File newFile = new File(filename);
                        FileOutputStream os = new FileOutputStream(newFile);
                        os.write(f.getBytes());
                        os.close();
                        f.transferTo(newFile);
                        //上传到OSS
                        String uploadUrl = aliyunOSSUtil.upload(newFile);
                        list.add(uploadUrl);
                    }
                }
                str = StringUtils.join(list, ",");
               /* String[]  strs=str.split(",");
                for (int i=0;i<strs.length;i++){
                    list1.add(strs[i]);
                }

                for (int i=0;i<list1.size();i++){
                    System.out.println(list1.get(i)+">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                }*/
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return str;
    }

自己开发的出门必备小程序可以扫码体验交流交流

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要从阿里云oss下载文件,可以使用Java SDK提供的OSSClient类。以下是使用Spring Boot实现从阿里云oss下载文件的步骤: 1. 引入阿里云Java SDK和Spring Boot依赖 在pom.xml中添加以下依赖: ``` <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 配置阿里云oss参数 在application.properties或application.yml中添加以下阿里云oss参数: ``` aliyun.oss.endpoint=<your endpoint> aliyun.oss.accessKeyId=<your accessKeyId> aliyun.oss.accessKeySecret=<your accessKeySecret> aliyun.oss.bucketName=<your bucketName> ``` 3. 实现文件下载接口 在Spring Boot的Controller中添加文件下载接口,使用OSSClient类下载指定文件: ``` @RestController public class FileController { @Autowired private OSSClient ossClient; @GetMapping("/download") public void download(@RequestParam String objectName, HttpServletResponse response) throws IOException { OSSObject ossObject = ossClient.getObject(bucketName, objectName); InputStream inputStream = ossObject.getObjectContent(); response.setHeader("Content-Disposition", "attachment;filename=" + objectName); response.setContentType("application/octet-stream"); IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); } } ``` 在上面的例子中,我们使用了@RequestParam注解来获取文件名,然后使用OSSClient类下载文件。最后,使用response将文件返回给客户端。 注意:在使用完OSSClient后,需要及时关闭它以释放资源。可以在Spring Boot的配置类中添加@PreDestroy注解来关闭OSSClient: ``` @Configuration public class OSSConfig { @Value("${aliyun.oss.endpoint}") private String endpoint; @Value("${aliyun.oss.accessKeyId}") private String accessKeyId; @Value("${aliyun.oss.accessKeySecret}") private String accessKeySecret; @Value("${aliyun.oss.bucketName}") private String bucketName; @Bean public OSSClient ossClient() { return new OSSClient(endpoint, accessKeyId, accessKeySecret); } @PreDestroy public void destroy() { ossClient().shutdown(); } } ``` 以上就是使用Spring Boot阿里云oss下载文件的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值