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

相关文章
Springboot文件下载跨域问题解决方案
Springboot文件下载跨域问题解决方案
|
10月前
|
存储 Java 文件存储
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— logback.xml 配置文件解析
本文解析了 `logback.xml` 配置文件的详细内容,包括日志输出格式、存储路径、控制台输出及日志级别等关键配置。通过定义 `LOG_PATTERN` 和 `FILE_PATH`,设置日志格式与存储路径;利用 `&lt;appender&gt;` 节点配置控制台和文件输出,支持日志滚动策略(如文件大小限制和保存时长);最后通过 `&lt;logger&gt;` 和 `&lt;root&gt;` 定义日志级别与输出方式。此配置适用于精细化管理日志输出,满足不同场景需求。
2377 1
|
10月前
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于 xml 的整合
本教程介绍了基于XML的MyBatis整合方式。首先在`application.yml`中配置XML路径,如`classpath:mapper/*.xml`,然后创建`UserMapper.xml`文件定义SQL映射,包括`resultMap`和查询语句。通过设置`namespace`关联Mapper接口,实现如`getUserByName`的方法。Controller层调用Service完成测试,访问`/getUserByName/{name}`即可返回用户信息。为简化Mapper扫描,推荐在Spring Boot启动类用`@MapperScan`注解指定包路径避免逐个添加`@Mapper`
541 0
|
easyexcel Java UED
SpringBoot中大量数据导出方案:使用EasyExcel并行导出多个excel文件并压缩zip后下载
在SpringBoot环境中,为了优化大量数据的Excel导出体验,可采用异步方式处理。具体做法是将数据拆分后利用`CompletableFuture`与`ThreadPoolTaskExecutor`并行导出,并使用EasyExcel生成多个Excel文件,最终将其压缩成ZIP文件供下载。此方案提升了导出效率,改善了用户体验。代码示例展示了如何实现这一过程,包括多线程处理、模板导出及资源清理等关键步骤。
|
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配置信息就好了
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
软件开发常用之SpringBoot文件下载接口编写(下),Vue+SpringBoot文件上传下载预览,服务器默认上传是1M,可以调节,调节文件上传大小写法,图片预览,如何预览后下次还能看到,预览写法
|
存储 安全 Java
Spring Boot中的文件下载实现
Spring Boot中的文件下载实现
|
XML Java 测试技术
【SpringBoot】基于 Maven 的 pom.xml 配置详解
【SpringBoot】基于 Maven 的 pom.xml 配置详解
2034 0
【SpringBoot】基于 Maven 的 pom.xml 配置详解
|
前端开发
SpringBoot+vue实现文件下载
SpringBoot+vue实现文件下载
775 0
|
XML Java 数据库连接
Spring Boot整合Mybatis(注解版+XML版)
Spring Boot整合Mybatis(注解版+XML版)
356 0