前端react后端java实现提交antd form表单成功即导出压缩包

前端(React + Ant Design)

  1. 创建表单:使用<Form>组件来创建你的表单。

  2. 处理表单提交:在onFinish回调中发起请求到后端API,并处理响应。

javascript 复制代码
import React from 'react';
import { Form, Input, Button } from 'antd';

const MyForm = () => {
  const [form] = Form.useForm();

  const onFinish = async (values) => {
    try {
      // 提交表单数据给后端API,并等待响应
      const response = await fetch('/api/submit-form', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(values)
      });

      if (!response.ok) throw new Error('Network response was not ok');

      // 处理返回的文件流
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = 'exported.zip'; // 设置下载的文件名
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);

    } catch (error) {
      console.error('There was a problem with the form submission:', error);
    }
  };

  return (
    <Form form={form} name="my_form" onFinish={onFinish}>
      {/* 表单项 */}
      <Form.Item name="username" rules={[{ required: true, message: 'Please input your username!' }]}>
        <Input />
      </Form.Item>
      {/* 更多表单项... */}
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

export default MyForm;

后端(Java + Spring Boot)

假设使用的是Spring Boot作为Java后端框架,以下是如何处理前端请求并生成压缩包的示例代码:

  1. 接收表单数据:创建一个REST控制器来接收前端发送的表单数据。

  2. 生成压缩包:根据接收到的数据生成压缩包。

  3. 发送压缩包:将压缩包作为HTTP响应的一部分发送回前端。

首先,需要添加必要的依赖项到pom.xml中,例如commons-compress用于创建ZIP文件。

XML 复制代码
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.21</version>
</dependency>

然后,在控制器中处理请求:

java 复制代码
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/api")
public class FormController {

    @PostMapping("/submit-form")
    public void handleFormSubmit(@RequestBody Map<String, Object> formData, HttpServletResponse response) throws IOException {
        // 根据formData准备要压缩的文件或文件路径列表...

        // 设置响应头以指示这是一个文件下载
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=exported.zip");

        // 创建ZIP输出流
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            // 添加文件到ZIP存档...
            // 这里只是一个示例,你需要根据实际情况调整逻辑
            File fileToZip = new File("path/to/file.txt");
            FileInputStream fis = new FileInputStream(fileToZip);
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zipOut.putNextEntry(zipEntry);

            byte[] bytes = new byte[1024];
            int length;
            while ((length = fis.read(bytes)) >= 0) {
                zipOut.write(bytes, 0, length);
            }

            zipOut.closeEntry();
            fis.close();
        }
    }
}

请注意,上述代码片段是简化版的示例,实际应用中可能需要更复杂的逻辑来处理错误、验证以及确保安全性。此外,后端部分还需要根据实际需求调整文件的压缩逻辑。如果需要压缩多个文件或目录,或者有更复杂的需求,则可能需要引入其他库或工具来辅助完成任务。

相关推荐
以和为贵5 分钟前
🔥前端也能搞懂流式输出:从 SSE 到打字机效果
前端·人工智能·架构
阿成学长_Cain1 小时前
Linux telinit 命令详解:运行级别切换|关机重启|系统维护一站式掌握
linux·运维·前端·网络
淘源码d1 小时前
医学影像云PACS系统——PACS诊断工作站
java·源码·影像处理·医院管理系统·影像工作站·云pacs系统·dicom 标准通信
Patrick_Wilson1 小时前
最佳实践是有保质期的:从一次 CDN external 白屏事故说起
前端·性能优化·前端工程化
YHHLAI2 小时前
[特殊字符] Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·人工智能
nuIl2 小时前
我把 5 个编码 Agent 塞进了一个 npm 包
前端·agent·claude
L-影2 小时前
FastAPI 静态文件:Web 页面的“固定展柜”与“加速引擎”
前端·fastapi
NiceCloud喜云2 小时前
Anthropic 一周三连发:Cowork 多端、Fable 5 按需付费、J-space 论文的技术解读
java·服务器·网络·人工智能·ai
陪我去看海2 小时前
受够了 AI 写完代码留下一堆端口?我做了一个端口管理App!
前端·macos·vibecoding
Xuepoo2 小时前
我抛弃了 DOM,但保留了无障碍访问
前端