SpringBoot文件下载(Zip & Xml)

简介: SpringBoot文件下载(Zip & Xml)

SpringBoot文件下载(Zip & Xml)

1、 Zip

java-controller

/**
     *  下载某一个主模板下所有的子模板
     * @param topProtocol top主模板id
     * @return
     */
    @GetMapping(value = "downLoadXmlZip")
    @ApiOperation(value = "根据topProtocol获取模板zip", notes = "获取某一个protocol的xml文本")
    public void downLoadXmlZip(@NotNull(message = "根据topProtocol获取模板zip") Long topProtocol, HttpServletResponse response){
        try {
            // 调用 sfProtocolService 下载 XML 文件
            sfProtocolService.downLoadXmlZip(topProtocol, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

java-Service

void downLoadXmlZip(Long topProtocol, HttpServletResponse response) throws IOException;
@Override
    public void downLoadXmlZip(Long topProtocol, HttpServletResponse response) throws IOException {
        // 获取全部
        List<SfProtocolEntity> downloadList = sfProtocolService.getParentAndChildListIdName(topProtocol);
        List<Path> files = new ArrayList<>();
        downloadList.forEach(item -> {
            SfFilePathEntity sfFilePathEntity = sfFilePathService.getOne(new LambdaQueryWrapper<SfFilePathEntity>()
                    .eq(SfFilePathEntity::getProtocolId, item.getId()));
            files.add(Paths.get(sfFilePathEntity.getPath()));
        });
        String fileName = "模板文件.zip";
        // 设置相应头
        response.setContentType("application/zip");
        // 解决文件乱码
        FileUtils.setAttachmentResponseHeader(response,fileName);
        // 压缩多个文件到zip文件中,并且响应给客户端
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream())) {
            for (Path file : files) {
                try (InputStream inputStream = Files.newInputStream(file)) {
                    zipOutputStream.putNextEntry(new ZipEntry(file.getFileName().toString()));
                    StreamUtils.copy(inputStream, zipOutputStream);
                    zipOutputStream.flush();
                }
            }
        }
    }

java-utils

package cn.datax.service.data.metadata.util;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class FileUtils extends org.apache.commons.io.FileUtils
{
    /**
     * 下载文件名重新编码
     *
     * @param response 响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String percentEncodedFileName = percentEncode(realFileName);
        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);
        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }
    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException
    {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }
}

vue-api

// 下载某一个主模板下所有的子模板
export function downLoadXmlZip(id) {
  return request({
    url: '/data/metadata/stepForm/downLoadXmlZip?topProtocol=' + id,
    method: 'get',
    responseType: 'blob',
    headers:{ 'Content-Type': 'application/zip'}
  })
}

vue-componet

downLoadStepForm(id){
      downLoadXmlZip(id).then(response => {
        const blob = new Blob([response], { type: 'application/zip' });
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '模板文件.zip';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
        .catch(error => {
          console.error('Error downloading ZIP file:', error);
        });
    },

result

2、 Xml

java-controller

/**
     *  返回blob
     * @param protocol top主模板id
     * @return
     */
    @GetMapping("downLoadXml")
    @ApiOperation(value = "返回blob", notes = "返回blob")
    public void downLoadXml(@NotNull(message = "protocol不能是空") Long protocol, HttpServletResponse response){
        try {
            // 调用 sfProtocolService 下载 XML 文件
            sfProtocolService.downLoadXml(protocol, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

java-Service

void downLoadXml(Long protocol, HttpServletResponse response) throws UnsupportedEncodingException;
/**
     * 下载单个xml
     * @param protocol
     * @param response
     */
    @Override
    public void downLoadXml(Long protocol, HttpServletResponse response) throws UnsupportedEncodingException {
        SfFilePathEntity sfFilePathEntity = sfFilePathService.getOne(new LambdaQueryWrapper<SfFilePathEntity>()
                .eq(SfFilePathEntity::getProtocolId, protocol));
        String filePath = sfFilePathEntity.getPath();
        Path path = Paths.get(filePath);
        String fileName = path.getFileName().toString();
        // 设置响应头
        response.setContentType(MediaType.APPLICATION_XML_VALUE);
        FileUtils.setAttachmentResponseHeader(response,fileName);
        // 将文件内容写入响应的输出流
        try (InputStream inputStream = Files.newInputStream(new File(filePath).toPath())) {
            FileCopyUtils.copy(inputStream, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

java-utils

package cn.datax.service.data.metadata.util;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class FileUtils extends org.apache.commons.io.FileUtils
{
    /**
     * 下载文件名重新编码
     *
     * @param response 响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException
    {
        String percentEncodedFileName = percentEncode(realFileName);
        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
                .append(percentEncodedFileName)
                .append(";")
                .append("filename*=")
                .append("utf-8''")
                .append(percentEncodedFileName);
        response.setHeader("Content-disposition", contentDispositionValue.toString());
    }
    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException
    {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }
}

vue-api

//返回blob 下载某一个xml
export function downLoadXml(id) {
  return request({
    url: '/data/metadata/stepForm/downLoadXml?protocol=' + id,
    method: 'get',
    responseType: 'blob',
    headers:{ 'Content-Type': 'application/xml'}
  })
}

vue-componet

downLoad(row) {
      let id = row.id
      let name = row.label
      downLoadXml(id).then(response => {
        const blob = new Blob([response], {type: 'application/xml'});
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = `${name}.xml`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
    },
      // 将blob中文本解析出来  
      initXmlData(id) {
      this.previewType = "xml";
      downLoadXml(id).then(res => {
        const blob = new Blob([res], { type: 'text/plain' });
        this.blobToString(blob).then((result) => {
          console.log("result::",result); // "test"
          this.previewResult = result
          console.log("this.previewResultthis.previewResult::",this.previewResult)
        });
      })
    },

result

相关文章
|
7月前
|
Java
Springboot文件下载跨域问题解决方案
Springboot文件下载跨域问题解决方案
|
2月前
|
easyexcel Java UED
SpringBoot中大量数据导出方案:使用EasyExcel并行导出多个excel文件并压缩zip后下载
在SpringBoot环境中,为了优化大量数据的Excel导出体验,可采用异步方式处理。具体做法是将数据拆分后利用`CompletableFuture`与`ThreadPoolTaskExecutor`并行导出,并使用EasyExcel生成多个Excel文件,最终将其压缩成ZIP文件供下载。此方案提升了导出效率,改善了用户体验。代码示例展示了如何实现这一过程,包括多线程处理、模板导出及资源清理等关键步骤。
|
5月前
|
XML Java 关系型数据库
Action:Consider the following: If you want an embedde ,springBoot配置数据库,补全springBoot的xml和mysql配置信息就好了
Action:Consider the following: If you want an embedde ,springBoot配置数据库,补全springBoot的xml和mysql配置信息就好了
|
5月前
|
Java
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
|
5月前
|
存储 安全 Java
Spring Boot中的文件下载实现
Spring Boot中的文件下载实现
|
7月前
|
前端开发
SpringBoot+vue实现文件下载
SpringBoot+vue实现文件下载
441 0
|
7月前
|
XML Java 测试技术
【SpringBoot】基于 Maven 的 pom.xml 配置详解
【SpringBoot】基于 Maven 的 pom.xml 配置详解
990 0
【SpringBoot】基于 Maven 的 pom.xml 配置详解
|
7月前
|
XML Java 数据库连接
Spring Boot整合Mybatis(注解版+XML版)
Spring Boot整合Mybatis(注解版+XML版)
124 0
|
7月前
|
XML Java 数据库连接
SpringBoot - 整合MyBatis配置版(XML)并开启事务
SpringBoot - 整合MyBatis配置版(XML)并开启事务
429 0
|
7月前
|
XML SQL Java
springboot 项目启动报Has been loaded by XML or SqlProvider, ignoring the injection of the SQL的错误的解决方案
springboot 项目启动报Has been loaded by XML or SqlProvider, ignoring the injection of the SQL的错误的解决方案
881 0