华为云obs文件上传下载

package org.jeecg.modules.controller;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.BaseController;

import org.jeecg.common.api.vo.R;
import org.jeecg.common.api.vo.TableDataInfoGenerics;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.modules.service.TestService ;
import org.jeecgframework.boot.entity.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/test")
@Slf4j
public class TestController {

    @Autowired
    private TestService testService;


    //上传
    @PostMapping(value = "/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<?> wctTaskRepeat(@RequestParam(value = "taskId", required = true) String taskId, @RequestParam(value = "checkRepeatFile")  String checkRepeatFile, @RequestParam(value = "checkRepeatScore", required = true)  String checkRepeatScore, @RequestParam(value = "file", required = true)  MultipartFile file) {
        return R.ok(testService.add(taskId,checkRepeatFile,checkRepeatScore,file));
    }

    //下载
    @PostMapping(value = "/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam("fileUrls") List<String> fileUrls) {
        testService.downloadFile(request,response,fileUrls);
    }


}






接口层

package org.jeecg.modules.service;

import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecgframework.boot.entity.Test;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


public interface TestService extends IService<Test> {

    Boolean add(String taskId, String checkRepeatFile, String checkRepeatScore, MultipartFile file);



    void downloadFile(HttpServletRequest request, HttpServletResponse response,List<String> fileUrls);
}

业务层

package org.jeecg.modules.service.impl;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import org.jeecg.modules.config.HWOBSConfig;
import org.jeecg.modules.mapper.TestResultMapper;
import org.jeecg.modules.service.TestResultService;
import org.jeecgframework.boot.entity.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


@Service
public class TestImpl extends ServiceImpl<TestResultMapper, Test> implements ActRepeatResultService {

    @Autowired
    HWOBSConfig hwobsConfig;

    @Override
    public Boolean add(String taskId, String checkRepeatFile, String checkRepeatScore, MultipartFile file) {
        Test test= new Test();
        test.setTaskId(taskId);
        test.setCheckRepeatFile(checkRepeatFile);
        test.setCheckRepeatScore(checkRepeatScore);
        test.setFileUrl(fileUpload(file));
        test.setCreateTime(new Date());
        return save(test);
    }



    public void downloadFile(HttpServletRequest request, HttpServletResponse response,List<String> fileUrls)  {
        //压缩包名称
        String zipFileName = "测试.zip";
        try {
            downloadZip1(zipFileName,fileUrls,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    //文件单个下载响应给前端
    public void downloadZip(String filesPath, HttpServletResponse response) throws Exception {
        ObsClient obsClient = hwobsConfig.getInstance();
        OutputStream bos = null;
        try {
            response.setContentType("application/force-download");// 设置强制下载不打开            
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("aa.pdf", "UTF-8"));
            // 流式下载
            ObsObject obsObject = obsClient.getObject(hwobsConfig.getBucketName(), filesPath);
            // 读取对象内容
            System.out.println("Object content:");
            InputStream input = obsObject.getObjectContent();
            byte[] b = new byte[1024];
            bos = response.getOutputStream();
            int len;
            while ((len = input.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            response.flushBuffer();
            System.out.println("getObjectContent successfully");
            bos.close();
            input.close();
        } catch (ObsException | FileNotFoundException e) {
            e.printStackTrace();
        }finally {
            hwobsConfig.destroy(obsClient);
        }
    }



     //obs文件批量下载,打压缩包推送前端
    public void downloadZip1(String zipFileName, List<String> filesPath, HttpServletResponse response) {
        ObsClient obsClient = null;
        try {
            obsClient = hwobsConfig.getInstance();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
            try (ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()))) {
                for (String filePath : filesPath) {
                    filePath=filePath.replace(hwobsConfig.getBackHeadUrl(),"");
                    if(StringUtils.isBlank(filePath)){
                        continue;
                    }
                    ObsObject obsObject = obsClient.getObject(hwobsConfig.getBucketName(), filePath);
                    String zipEntryName = filePath; // 或根据需要处理zip中的文件名
                    if(StringUtils.isNotBlank(filePath)){
                        String[] split = filePath.split("/");
                        zipEntryName=split[1].substring(36);
                    }
                    out.putNextEntry(new ZipEntry(zipEntryName));
                    try (BufferedInputStream in = new BufferedInputStream(obsObject.getObjectContent())) {
                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1) {
                            out.write(buffer, 0, bytesRead);
                        }
                    }
                }
                out.finish();
            } catch (IOException e) {
                // 处理IO异常
                e.printStackTrace(); // 或使用日志框架记录异常
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (Exception e) {
            // 处理其他异常
            e.printStackTrace(); // 或使用日志框架记录异常
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            if (obsClient != null) {
                hwobsConfig.destroy(obsClient);
            }
        }
    }

    /**
     *上传文件到obs
    */
    public String fileUpload(MultipartFile uploadFile) {
        ObsClient obsClient = null;
        String objectUrl = "";
        try {
            String bucketName = hwobsConfig.getBucketName();
            obsClient = hwobsConfig.getInstance();
            // 判断桶是否存在
            boolean exists = obsClient.headBucket(bucketName);
            if (!exists) {
                // 若不存在,则创建桶
                HeaderResponse response = obsClient.createBucket(bucketName);
            }
            // 上传文件到OBS
            long size = uploadFile.getSize();
            //1 200 兆字节=209715200 字节  1long=4个字节
            if (size <= 0) {
                throw new ServiceException("上传的文件为空");
            }
            if (size > 52428800) {
                throw new ServiceException("单次上传不能超过200M");
            }
            //增加文件夹
            String yyyyMMdd = DateUtil.format(new Date(), "yyyyMMdd");
            String objectKey = yyyyMMdd+"/"+ UUID.randomUUID() + uploadFile.getOriginalFilename();
            PutObjectRequest request = new PutObjectRequest(bucketName, objectKey, uploadFile.getInputStream());
            PutObjectResult putObjectResult = obsClient.putObject(request);
            objectUrl = objectKey;
        } catch (ObsException e) {
            // 请求失败,打印http状态码
            System.out.println("HTTP Code:" + e.getResponseCode());
            // 请求失败,打印服务端错误码
            System.out.println("Error Code:" + e.getErrorCode());
            // 请求失败,打印详细错误信息
            System.out.println("Error Message:" + e.getErrorMessage());
            // 请求失败,打印请求id
            System.out.println("Request ID:" + e.getErrorRequestId());
            System.out.println("Host ID:" + e.getErrorHostId());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("putObject failed");
            // 其他异常信息打印
            e.printStackTrace();
        } finally {
            hwobsConfig.destroy(obsClient);
        }
        return hwobsConfig.getBackHeadUrl()+objectUrl;
    }
}
HWOBSConfig配置类
package org.jeecg.modules.config;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Description: 华为云OBS配置类
 */
@Slf4j
@Data
@Component
public class HWOBSConfig {
    /**
     * 访问密钥AK  yml文件中配置
     */
    @Value("${test.obs.accessKey}")
    private String accessKey;

    /**
     * 访问密钥SK yml文件中配置
     */
    @Value("${test.obs.securityKey}")
    private String securityKey;

    /**
     * 终端节点 yml文件中配置
     */
    @Value("${test.obs.endPoint}")
    private String endPoint;

    /**
     * 桶  yml文件中配置
     */
    @Value("${test.obs.bucketName}")
    private String bucketName;

    /**
     * 服务直接访问地址,通过nginx转发的接口用
     */
    
    @Value("${test.obs.backHeadUrl}")
    private String backHeadUrl;

    /**
     * @Description 获取OBS客户端实例
     * @return
     * @return: com.obs.services.ObsClient
     */
    public ObsClient getInstance() {
        return new ObsClient(accessKey, securityKey, endPoint);
    }

    /**
     * @Description 销毁OBS客户端实例
     * @param: obsClient
     * @return
     */
    public void destroy(ObsClient obsClient){
        try {
            obsClient.close();
        } catch (ObsException e) {
//            log.error("obs执行失败", e);
        } catch (Exception e) {
//            log.error("执行失败", e);
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
华为云OBS(Object Storage Service)是一种可扩展的云存储服务,通过它可以方便地进行文件的存储、备份和批量上传等操作。 要实现华为云OBS文件的批量上传,我们可以采用以下步骤: 1. 首先,需要在华为云上创建一个OBS存储桶。在华为云控制台中,选择OBS服务,然后点击创建存储桶,并根据需要配置存储桶的相关参数。 2. 在本地计算机上准备好需要上传的文件,可以将这些文件放在同一个文件夹中,方便进行批量操作。 3. 接下来,可以使用华为云提供的OBS SDK,根据编程语言的不同选择相应的SDK版本。一般可以通过安装SDK的方式,引入SDK到项目中。 4. 在代码中,首先需要进行OBS的验证,即提供访问华为云账号的认证信息(Access Key和Secret Key),以便进行API调用。 5. 在验证通过之后,可以使用SDK提供的方法,选择需要上传的文件路径和OBS存储桶的名称等相关参数。然后使用循环或批量操作的方式,依次上传文件。 6. 上传过程中,可以监听上传的进度和状态,以便得知文件上传是否成功。 7. 完成文件上传后,可以通过华为云控制台,或者使用OBS SDK提供的API方法,查看已上传的文件。 总的来说,华为云OBS文件的批量上传可以通过使用OBS SDK来实现,在代码中调用相应的API方法,依次上传文件即可。通过这种方式,可以提高上传效率,简化操作步骤,方便批量上传大量文件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值