【COS文件上传下载】

 		<dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.6.54</version>
        </dependency>
package com.example.completablefuture.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;

import com.example.completablefuture.config.CosConfig;
import com.example.completablefuture.config.OSSConfig;
import com.example.completablefuture.listener.CommonListen;
import com.example.completablefuture.model.DeliveryGoodExcel;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Author pangzhihao
 * @Date 2021/9/22 19:21
 * @Version 1.0
 */
@RestController
@RequestMapping("/excel/")
@Slf4j
public class ExcelController {

    @Autowired
    private CosConfig cosConfig;

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        //读取COS 获取文件并解析操作数据库
        //获取相关配置
        String bucketName = cosConfig.getBucketname();
        String endpoint = cosConfig.getEndpoint();
        String endpointTemp = endpoint.substring(endpoint.indexOf(".") + 1);
        endpointTemp = endpointTemp.substring(0, endpointTemp.indexOf("."));
        String accessKeyId = cosConfig.getAccessKeyId();
        String accesskeySecret = cosConfig.getAccessKeySecret();
        COSCredentials cred = new BasicCOSCredentials(accessKeyId, accesskeySecret);
        Region region = new Region(endpointTemp);
        ClientConfig clientConfig = new ClientConfig(region);
        //创建客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        //获取原生文件名 xxx.cvs
        String originalFilename = file.getOriginalFilename();
        //JDK8的日期格式化
        LocalDateTime ldt = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        //拼装路径,cos上存储的路径
        String folder = dtf.format(ldt);
        //随机数
        String fileName = generateUUID();
        //.csv
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //新文件名
        String newFileName = "excel/" + folder + "/" + fileName + extension;
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            //文件的大小
            objectMetadata.setContentLength(file.getSize());
            //文件的类型
            objectMetadata.setContentType(file.getContentType());
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newFileName, file.getInputStream(), objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            log.info("newFileName:{}", newFileName);
            if (putObjectResult != null) {
                System.out.println(JSON.toJSONString(putObjectResult));
                String fileAccessUrl = "https://" + bucketName + "." + endpoint + "/" + newFileName;
                System.out.println(fileAccessUrl);
                return fileAccessUrl;
            }
        } finally {
            //cos关闭服务,不然会造成OOM
            cosClient.shutdown();
        }
        return null;
    }

    /**
     * 导入
     */
    @RequestMapping("importExcel")
    @ResponseBody
    public void importExcel(String newFileName) {
        //读取COS 获取文件并解析操作数据库
        //获取相关配置
        String bucketName = cosConfig.getBucketname();
        String endpoint = cosConfig.getEndpoint();
        String endpointTemp = endpoint.substring(endpoint.indexOf(".") + 1);
        endpointTemp = endpointTemp.substring(0, endpointTemp.indexOf("."));
        String accessKeyId = cosConfig.getAccessKeyId();
        String accesskeySecret = cosConfig.getAccessKeySecret();
        COSCredentials cred = new BasicCOSCredentials(accessKeyId, accesskeySecret);
        Region region = new Region(endpointTemp);
        ClientConfig clientConfig = new ClientConfig(region);
        //创建客户端
        COSClient cosClient = new COSClient(cred, clientConfig);

        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, newFileName);
        COSObject cosObject = cosClient.getObject(getObjectRequest);
        COSObjectInputStream cosObjectInput = cosObject.getObjectContent();
        try {
            List<Object> objects = EasyExcel.read(cosObjectInput, DeliveryGoodExcel.class, new CommonListen()).sheet().doReadSync();
            log.info("xxxxx:{}", objects);
        } finally {
            //cos关闭服务,不然会造成OOM
            cosClient.shutdown();
        }

    }


    private static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 导出
     */
//    @RequestMapping("exportExcel")
//    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        // 读取数据库返回数据
//        log.info("请求:{}", request);
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");
//        String age = request.getParameter("age");
//        Map<String, Object> params = new HashMap<String, Object>();
//        if (!StringUtils.isEmpty(username)) {
//            params.put("username", username);
//        }
//        if (!StringUtils.isEmpty(password)) {
//            params.put("password", password);
//        }
//        if (!StringUtils.isEmpty(age)) {
//            params.put("age", Integer.valueOf(age));
//        }
//        XXXExcel excel = new XXXExcel();
//        excel.setAge(Integer.valueOf(age));
//        excel.setUsername(username);
//        excel.setPassword(password);
//        List<XXXExcel> rows = new ArrayList<>();
//        rows.add(excel);
//        downloadExcel(response, XXXExcel.class, rows);
//    }
//
//    private void downloadExcel(HttpServletResponse response, Class<?> clazz,
//                               List<?> data) throws IOException {
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("审计日志.csv", "UTF8"));
        response.setHeader("FileName", URLEncoder.encode("审计日志.xlsx", "UTF8"));
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//
//        EasyExcel.write(byteArrayOutputStream, XXXExcel.class).sheet().doWrite(data);
//        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
//
//        //读取OSS 获取文件并解析操作数据库
//        //获取相关配置
//        String bucketname = ossConfig.getBucketname();
//        String endpoint = ossConfig.getEndpoint();
//        String accessKeyId = ossConfig.getAccessKeyId();
//        String accesskeySecret = ossConfig.getAccessKeySecret();
//        //创建OSS对象
//        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accesskeySecret);
//
//        //新文件名
//        String newFileName = "excel/" + "123.csv";
//
//        try {
//            PutObjectResult putObjectResult = ossClient.putObject(bucketname, newFileName, byteArrayInputStream);
//            if (putObjectResult != null) {
//                String imgUrl = "https://" + bucketname + "." + endpoint + "/" + newFileName;
//                System.out.println(imgUrl);
//            }
//        } finally {
//            //oss关闭服务,不然会造成OOM
//            ossClient.shutdown();
//        }
        Sheet sheet = new Sheet(1, 0, clazz);
        writer.write(data, sheet);
        writer.finish();
        out.flush();
//    }


}
tx:
  cos:
    endpoint: cos.ap-beijing.myqcloud.cos
    access-key-id: AKIDrWv3uUmnX0C7l9G6evve6G9l6AsTw
    access-key-secret: D9nBH6evve6HBoAE2YnlSs1tUors
    bucket-name: express-13045xx
package com.example.completablefuture.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @Author pangzhihao
 * @Date 2021/9/29 19:03
 * @Version 1.0
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "tx.cos")
public class CosConfig {

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketname;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值