Java中字符串生成文件打包为zip下载

Java中字符串生成文件打包为zip下载

需求

目前有freemarker引擎生成的插值后html字符串数据,现在需求是下载到前端;
需要两种方式下载:一,html单个文件 二,多个文件下载打包成zip下载

话不多说直接上代码

编写工具类

@Slf4j
public class FileDownloadUtils {

    @Data
    public static class FileVo{

        private String fileName;
        private String string;

        public FileVo(){}

        public FileVo(String fileName,String string){
            this.fileName=fileName;
            this.string=string;
        }
    }
    
    public static Boolean fileDownLoad(FileVo vo, HttpServletResponse response)  {
        if(StringUtils.isEmpty(vo.getString())){
            throw new ServiceException(500,"[内容为空]");
        }
        String fileName = vo.getFileName();// 文件名
        try {
            fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        OutputStream os=null;
        try {
            byte[] bytes = vo.getString().getBytes(StandardCharsets.UTF_8);
            os= response.getOutputStream();
            os.write(bytes);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(500,"[下载失败]");
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

	/**
     * 多个html字符串打包成zip下载
     */
    public static void zipFileDownload(Map<String, byte[]> byteList,HttpServletResponse response) {
        try {
            String fileName = System.currentTimeMillis()+".zip";// .zip名
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
            OutputStream outputStream = response.getOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
            byteList.forEach((k, v) -> {
                //写入一个条目,我们需要给这个条目起个名字,相当于起一个文件名称
                try {
                    zipOutputStream.putNextEntry(new ZipEntry(k));
                    zipOutputStream.write(v);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("写入文件失败");
                }
            });
            //关闭条目
            zipOutputStream.closeEntry();
            zipOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("压缩文件失败");
        }
    }
}

又是一个小细节
解决在前端显示文件名中文乱码

String fileName = vo.getFileName();// 文件名
try {
    fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

业务层调用方法

先在controller层将response传到service


@GetMapping(value = "/download")
public void download(@RequestParam String id, HttpServletResponse response) {
    fileDownloadService.fileDownLoad(id,response);
}

service调用
单个文件下载

FileDownloadUtils.FileVo vo = new FileDownloadUtils.FileVo("filename"+".txt","filebodyString");
FileDownloadUtils.fileDownLoad(vo,response);

多个文件打包zip下载


Map<String, byte[]> map = new HashMap<String, byte[]>();
//String直接getBytes() 就可以获得byte[]数组
map.add("filename"+".txt","filebodyString".getBytes());
FileDownloadUtils.zipFileDownload(map ,response);

END

如果你想知道freemarker在我这个需求中是如何使用的,你可以翻阅上一篇博客

码字不易,如果对你有帮助,请给个三连吧!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java的DOM和ZipOutputStream来实现将字符串生成xml文件并压缩成zip的功能。以下是一个简单的实现示例: ```java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class XmlZipper { public static void main(String[] args) throws Exception { // 生成xml字符串 String xmlString = "<root><message>Hello World!</message></root>"; // 将xml字符串转换为Document对象 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new ByteArrayInputStream(xmlString.getBytes())); // 创建zip文件 File zipFile = new File("example.zip"); ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); // 将xml写入zip文件 ZipEntry xmlEntry = new ZipEntry("example.xml"); zipOut.putNextEntry(xmlEntry); ByteArrayOutputStream xmlOut = new ByteArrayOutputStream(); document.setXmlStandalone(true); document.normalize(); document.getDocumentElement().normalize(); XmlUtils.writeXml(document, xmlOut); zipOut.write(xmlOut.toByteArray()); xmlOut.close(); zipOut.closeEntry(); // 关闭zip文件 zipOut.finish(); zipOut.close(); } public static class XmlUtils { public static void writeXml(Document document, ByteArrayOutputStream out) throws Exception { javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance(); javax.xml.transform.Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document); javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(out); transformer.transform(source, result); } } } ``` 这段代码将生成一个名为example.zip的压缩文件,并在其包含了一个名为example.xml的xml文件。你可以使用ZipFile类来解压缩该文件,并读取其的xml内容。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值