栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【COS文件上传下载】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【COS文件上传下载】

 		
            com.qcloud
            cos_api
            5.6.54
        
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.*;


@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 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 params = new HashMap();
//        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 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;


@Data
@Configuration
@ConfigurationProperties(prefix = "tx.cos")
public class CosConfig {

    private String endpoint;

    private String accessKeyId;

    private String accessKeySecret;

    private String bucketname;

}
转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号