java创建txt文档写入内容并且上传至oss,以及下载oss的文件打成压缩包

创建txt文档写入内容,上传至oss代码

package com.fadu.app.util;

import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @Author: Wxy
 * @Description:字节数组输入流
 * @Date created in 16:27 2020/10/16
 */
public class FileUtils {

    private static final Logger log = Logger.getLogger(FileUtils.class);

    /**
     * @param stringInfo txt文件内容
     * @return
     */
    public static InputStream convertStrToIns(String stringInfo){
        try {
            InputStream inputStream = new ByteArrayInputStream(stringInfo.getBytes("UTF-8"));
            return inputStream;
        } catch (Exception e) {
            log.error(" 异常");
            return null;
        }
    }

}

package com.esign.util;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.esign.constant.ConfigConstant;
import com.fadu.app.util.Constant;
import org.apache.log4j.Logger;


import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

public class OSSUtils {

    private static final Logger log = Logger.getLogger(OSSUtils.class);

    //oss所在域,要加http:// 必填 获取的方式这里就不提了
    public static String endpoint = "";
    //密匙keyId 必填 获取的方式这里就不提了
    public static String accessKeyId = "";
    //密匙keySecret 获取的方式这里就不提了
    public static String accessKeySecret = "";

    /**
     * 上传文本文件至Oss
     *
     * @param bucketName      桶的名称
     * @param name            文件名
     * @param inputStream 上传网络流
     * @return
     */
    public static String uploadTxtFileToOSS(String bucketName, String name, InputStream inputStream) {
        try {
            log.info("ESIGN 文件开始上传至OSS");
            // 创建OSSClient实例
            OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            String objectName = name.concat(Constant.TXT_FILE_SUFFIX);
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("text/plain");
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, inputStream, metadata);
            // 关闭OSSClient
            ossClient.shutdown();
            // 返回地址 根据自己的oss路径拼接 不需要的话可以不拿 
            String filePath;
            log.info("ESIGN 文件上传至OSS路径:" + filePath);
            return filePath;
        } catch (Exception e) {
            log.error("上传失败", e);
            return null;
        }
    }
}


至此上传的代码就完毕了。根据URL下载文件,并且打成压缩包代码放下面

 /**
     * 将当前的文件放到zip流中传出去
     * @param imageUrl 文件URL地址
     * @param imageName 文件名称
     * @param zipOutputStream zip输出流
     */
    public static void downLoadImage(String imageUrl,String imageName,ZipOutputStream zipOutputStream) {
        String suffix = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);

        if(StringUtils.isNotBlank(imageUrl)){
            BufferedInputStream in = null;
            try {
                imageName += "." + suffix;

                URL url = new URL(imageUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                conn.setRequestProperty(
                        "Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg,text/plain, "
                                + "application/x-shockwave-flash, application/xaml+xml, "
                                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                                + "application/x-ms-application, application/vnd.ms-excel, "
                                + "application/vnd.ms-powerpoint, application/msword, */*");
                conn.setRequestProperty("Accept-Language", "zh-CN");
                conn.setRequestProperty("Charset", "UTF-8");

                InputStream inStream = conn.getInputStream();
                if(inStream == null) {
                    throw new Exception("获取压缩的数据项失败! 图片名为:" + imageName);
                }else {
                    in = new BufferedInputStream(inStream);
                }

                // 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样
                //ZipEntry zipEntry = new ZipEntry("图片/" + imageName);

                ZipEntry zipEntry = new ZipEntry(imageName);
                // 定位到该压缩条目位置,开始写入文件到压缩包中
                zipOutputStream.putNextEntry(zipEntry);

                byte[] bytes = new byte[1024 * 5]; // 读写缓冲区
                int read = 0;
                while ((read = in.read(bytes)) != -1) {
                    zipOutputStream.write(bytes, 0, read);
                }

                IOUtils.closeQuietly(inStream); // 关掉输入流
                IOUtils.closeQuietly(in); // 关掉缓冲输入流
                zipOutputStream.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
   /**
     * 获取多个文件的二进制
     * @param imgUrls 多个文件URL地址数组
     * @param names 多个文件的文件名
     * @return
     * @throws Exception
     */
    public static byte[] getImagesByte(String[] imgUrls,List<String> names) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);

        for (int i = 0; i < imgUrls.length; i++) {
            // 获取文件名称
            String imgName = imgUrls[i].substring(imgUrls[i].lastIndexOf("/")+1);
            String imageName = imgName.substring(0,imgName.lastIndexOf("."));
            if (StringUtils.isNotBlank(names.get(i))) {
                imageName = names.get(i);
            }
            // 将当前的文件放到zip流中传出去
            downLoadImage(imgUrls[i], imageName, zipOutputStream);
        }
        IOUtils.closeQuietly(zipOutputStream);
        return outputStream.toByteArray();
    }
 /**
     * 下载多个文件的压缩包
     * @param request
     * @param response
     * @param imgUrls 多个文件URL地址数组
     * @param zipName 压缩包名称
     * @throws Exception
     */
    public static void downloadImagesZip(HttpServletRequest request, HttpServletResponse response, String[] imgUrls,String zipName,List<String> name) throws Exception {
        // 获取多张图片的二进制
        byte [] data = getImagesByte(imgUrls,name);

        response.reset();
//        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
        response.setHeader("Content-Disposition", "attachment; filename=\""
                + new String(zipName.getBytes("utf-8"),"ISO-8859-1")+".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream;charset=UTF-8");

        IOUtils.write(data, response.getOutputStream());
        IOUtils.closeQuietly(response.getOutputStream());
    }

到这里就结束了,不懂的地方看注释 代码还是挺容易的。
直接调用downloadImagesZip方法就可以进行打包下载了。
需要注意的一点是 下载文件的Url路径不能包含中文和特殊字符,否则会报错的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值