java jquery xml http request 原生 post ajax 文件打包上传下载

<html>

<head>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body>
    <form id="form" method="post" enctype="multipart/form-data">
        file: <input type="file" name="files" multiple />
        <input id="submit" type="button" value="submit" />
    </form>
    <script>
        $(function () {
            $("#submit").click(function () {
                let formData = new FormData($("#form")[0]);

                let url = "http://localhost:8701/auth/oss_zip_down";
                let xhr = new XMLHttpRequest();

                xhr.open("post", url, true);
                xhr.responseType = "blob";
                xhr.setRequestHeader("Authorization",
                    "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuaWNrbmFtZSI6IiIsInJvbGUiOiIiLCJpZCI6MTM4MDc5NDY1NDUwNzA0MDgzMSwiZXhwIjoxNjQ4OTAzODEwODgyLCJ1c2VybmFtZSI6InN1cGVyIn0.UG-waVzA9SMq4gIIf5fXy23OjwTdb3WlK5uvGeFmqmQ"
                    )
                xhr.send(formData);
                xhr.onload = function () {
                    if (this.status == 200) {
                        let blob = this.response;
                        let a = document.createElement('a');
                        a.download = "files.zip";
                        a.href = window.URL.createObjectURL(blob);
                        a.click();
                    }

                }
            });
        });
    </script>
</body>

</html>

import lombok.Getter;
import lombok.Setter;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipTools {
    private ZipTools() {
    }

    /**
     * 压缩上传的文件并下载
     *
     * @param files    List<MultipartFile>
     * @param response HttpServletResponse
     * @throws IOException 文件处理异常
     */
    public static void compressionAndDown(List<MultipartFile> files, HttpServletResponse response) throws IOException {
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=files.zip");
        response.addHeader("Content-Length", "");
        response.setContentType("application/octet-stream");

        List<ZipFile> zipFiles = getZipFiles(files);
        compressionFormZipFile(zipFiles, response.getOutputStream());
    }

    /**
     * 获取ZipFile
     *
     * @param files List<MultipartFile>
     * @return List<ZipFile>
     */
    public static List<ZipFile> getZipFiles(List<MultipartFile> files) {
        return files.stream().map(i -> {
            ZipFile zipFile = null;
            try {
                zipFile = new ZipFile();
                zipFile.setIs(i.getInputStream());
                zipFile.setName(i.getOriginalFilename());
            } catch (IOException e) {
                e.printStackTrace();
            }
            return zipFile;
        }).collect(Collectors.toList());
    }

    /**
     * 压缩zip file
     *
     * @param files ZipFile {inputStream,name} 文件输入流,文件全称
     * @param os    HttpServletResponse getOutputStream()
     */
    public static void compressionFormZipFile(List<ZipFile> files, OutputStream os) {
        try (ZipOutputStream zipOut = new ZipOutputStream(os)) {
            files.forEach(i -> {
                try {
                    InputStream is = i.getIs();
                    ZipEntry zipEntry = new ZipEntry(i.getName());
                    zipOut.putNextEntry(zipEntry);
                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = is.read(bytes)) >= 0) {
                        zipOut.write(bytes, 0, length);
                    }
                    zipOut.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件流并输出二进制流
     *
     * @param inputStreams 二进制文件输入流
     * @param outputStream HttpServletResponse getOutputStream()
     * @param fileType     .png ...
     */
    public static void compressionFormInputStream(List<InputStream> inputStreams, OutputStream outputStream, String fileType) {
        try (ZipOutputStream zipOut = new ZipOutputStream(outputStream);) {
            //向压缩包中添加多个文件
            inputStreams.forEach(i -> {
                try {
                    ZipEntry zipEntry = new ZipEntry(System.currentTimeMillis() + fileType);
                    zipOut.putNextEntry(zipEntry);
                    byte[] bytes = new byte[1024];
                    int length;
                    while ((length = i.read(bytes)) >= 0) {
                        zipOut.write(bytes, 0, length);
                    }
                    zipOut.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

    @Getter
    @Setter
    static
    class ZipFile {
        private InputStream is;
        private String name;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等一场春雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值