阿里云对象存储OSS批量上传,单个上传,批量删除,单个删除!

请自行替换秘钥:

复制代码
#阿里云 OSS src/main/resources/application.properties
#不同的服务器,地址不同
aliyun.oss.file.endpoint=https://oss-cn-hangzhou.aliyuncs.com
aliyun.oss.file.accessKeyId=LTAI5t9wUqCoD42qPGRy8S
aliyun.oss.file.accessKeySecret=WV9W6erbdF2oqH4KIlo5BzNrwaP
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketName=zhurenjin-workspace

多个文件批量上传,单个上传,工具类:

java 复制代码
public Map<String, Object> Upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        int iPoint = originalFilename.lastIndexOf(".");
        String fileTypePre = originalFilename.substring(0,iPoint);
        String fileType = originalFilename.substring(iPoint);
        String fileName = UUID.randomUUID().toString()+fileTypePre+fileType;

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        // PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
        // 创建PutObject请求。
       ossClient.putObject(bucketName,fileName,inputStream);
       // https://zhurenjin-workspace.oss-cn-hangzhou.aliyuncs.com/exampledir/exampleobject.jpg
       String imgUrl = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/"+fileName;
       ossClient.shutdown();

        Map<String ,Object> re = new HashMap<String ,Object>();
        Map<String ,Object> imgList = new HashMap<String ,Object>();
        imgList.put("imageUrl",imgUrl);
        re.put("code",200);
        re.put("msg","上传成功");
        re.put("data",imgList);

        return re;

    }

单个文件上传

java 复制代码
@PostMapping("uploadAliyunOSSByUtils")
     public AjaxResult uploadAliyunOSSByUtils( @RequestParam("files") MultipartFile img) throws IOException {
        if (!(img.getOriginalFilename().endsWith(".png")) && !(img.getOriginalFilename().endsWith(".jpg")) && !(img.getOriginalFilename().endsWith(".PNG"))) {
            try {
                return AjaxResult.error("文件类型错误,只能为png或者jpg");
            } catch (Exception e) {
                  throw new RuntimeException(e);
            }
        }
        // 调用阿里云工具类进行文件上传
        AliOSSUtils aliOSSUtils = new AliOSSUtils();
        Map<String, Object> upload = aliOSSUtils.Upload(img);
        return AjaxResult.success(upload);
    }

多个文件上传

java 复制代码
 // 阿里云存储(多张图片)
    @PostMapping("uploadAliyunOSSByUtilsArrayFils")
    public AjaxResult uploadAliyunOSSByUtilsArrayFils( MultipartFile[] imgList) throws IOException {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        // List<Object> objectsImages = new ArrayList<>();
        List<Map<String, Object>> objectsImages = new ArrayList<>();
        // 调用阿里云工具类进行文件上传
        for (MultipartFile img : imgList){
            Map<String, Object> uploadImd = aliOSSUtils.Upload(img);
            Map<String, Object> New_ = new HashMap<>();
            New_.put("strImg",uploadImd);
            objectsImages.add(New_);
            // objectsImages.add(uploadImd);
        }
        return AjaxResult.success(objectsImages);
    }

单个删除

java 复制代码
 // 阿里云删除单张图片
    @PostMapping("deleteAliyunOSSByUtils")
    public AjaxResult deleteAliyunOSSByUtils(@RequestBody Map<String,String> img) throws IOException {
        // 创建OSSClient实例。

        System.out.println(img);
        boolean b = aliOSSUtils.deleteFile(img);
        return AjaxResult.success(b);
    }

多个删除

java 复制代码
 @PostMapping("deleteAliyunOSSByUtilsArrayList")
    public AjaxResult deleteAliyunOSSByUtilsArrayList(@RequestBody List<String> imgList) throws IOException {
        // 创建OSSClient实例。

         boolean b = aliOSSUtils.deleteAllFile(imgList);
        return AjaxResult.success(b);
    }

工具类

java 复制代码
 /*删除工具类《单个》*/
    public boolean deleteFile(Map<String,String> fileUrl){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String img = fileUrl.get("img");
        int begin = (endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/").length(); //找到文件路径的开始下标
        String deleteUrl = img.substring(begin);
        try {
            // 删除文件请求
            VoidResult voidResult = ossClient.deleteObject(bucketName, deleteUrl);
            System.out.println(voidResult+"删除chengg11111??222");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
    /*删除工具类《多个》,主要就是要获取到相应的文件后缀,String deleteUrl = objImg.substring(begin);*/
    public boolean deleteAllFile(List<String> keys){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        List<String> keysBox= new ArrayList<>();
        int begin = (endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/").length(); //找到文件路径的开始下标
        for(String objImg : keys) {
            String deleteUrl = objImg.substring(begin);
            keysBox.add(deleteUrl);
        }
        try {
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keysBox).withEncodingType("url"));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            try {
                for(String obj : deletedObjects) {
                    String deleteObj =  URLDecoder.decode(obj, "UTF-8");
                    System.out.println(deleteObj);
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

学以致用,多做记录

相关推荐
一只爱打拳的程序猿3 分钟前
【Spring】更加简单的将对象存入Spring中并使用
java·后端·spring
杨荧4 分钟前
【JAVA毕业设计】基于Vue和SpringBoot的服装商城系统学科竞赛管理系统
java·开发语言·vue.js·spring boot·spring cloud·java-ee·kafka
minDuck6 分钟前
ruoyi-vue集成tianai-captcha验证码
java·前端·vue.js
为将者,自当识天晓地。25 分钟前
c++多线程
java·开发语言
daqinzl33 分钟前
java获取机器ip、mac
java·mac·ip
激流丶1 小时前
【Kafka 实战】如何解决Kafka Topic数量过多带来的性能问题?
java·大数据·kafka·topic
Themberfue1 小时前
Java多线程详解⑤(全程干货!!!)线程安全问题 || 锁 || synchronized
java·开发语言·线程·多线程·synchronized·
时差9531 小时前
【面试题】Hive 查询:如何查找用户连续三天登录的记录
大数据·数据库·hive·sql·面试·database
让学习成为一种生活方式1 小时前
R包下载太慢安装中止的解决策略-R语言003
java·数据库·r语言
晨曦_子画1 小时前
编程语言之战:AI 之后的 Kotlin 与 Java
android·java·开发语言·人工智能·kotlin