SpringBoot整合阿里云OSS存储服务 file.transferTo(newFile) oss文件的下载、删除

1.整合过程参考博客:
SpringBoot整合阿里云OSS

在这里插入图片描述
其中,看到其他地方说transferto()方法,是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘

参考博客:
transferto()方法 把内存中图片写入磁盘

2.删除oss指定文件

/** 删除oss文件  数据库信息和oss里面的文件同时删除
     * @description
     * @author    tony
     * @date  2019/12/9 21:54
     */
    @RequestMapping(value = "/delFile",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> delFile(String uuid) {

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("success",false);
        retMap.put("msg","删除失败");
        try {
            retMap = ossFileService.delFile(uuid);
        } catch (Exception e) {
            logger.info("============>文件删除 出现异常");
            retMap.put("msg","文件删除 出现异常");
            e.printStackTrace();
        }

        return retMap;
    }

service:

@Override
    public Map<String,Object> delFile(String uuid) {
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("success",false);
        retMap.put("msg","删除失败");

        // 创建OSSClient实例。
        OSSClient ossClient = AliyunOSSUtil.createOSSClient();
        OSSFile targetFile =ossFileRepository.getOne(uuid);

        String bucketName = targetFile.getBucketName();
        String urlSuffix = targetFile.getUrlSuffix();

        // 删除file.
        boolean exist = ossClient.doesObjectExist(bucketName, urlSuffix);
        if (!exist) {
            retMap.put("msg","文件不存在");
            return retMap;
        }

        ossClient.deleteObject(bucketName, urlSuffix); //oss 容器中删除文件
        ossFileRepository.deleteById(uuid);    //数据库中删除对应的文件信息

        retMap.put("success",true);
        retMap.put("msg","删除成功");

        ossClient.shutdown();
        return retMap;
    }

3.文件的下载

 // 创建OSSClient实例
 OSSClient ossClient = createOSSClient();
 Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 );// url过期时间为1天
 String url = ossClient.generatePresignedUrl(ossFile.getBucketName(),ossFile.getUrlSuffix(),expiration).toString();

获取到url,前台页面上点击url 即可完成文件的下载
参考博客:
于OSS服务器的文件上传以及文件下载

发布了98 篇原创文章 · 获赞 7 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37767455/article/details/103469123