提交动态创建的表单

Submit dynamically created form

我正在为我的一个项目使用 angular 2/4,我在提交请求时必须下载文件。我目前正在做。

this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
            .subscribe((data) => {

                let blob = new Blob([data.body], { 'type': 'application/octet-stream' });
                saveAs(blob, 'file.zip');
            })

文件大小可能非常大,所以我希望浏览器处理请求而不是解析数据并在应用程序端创建 blob。所以我在某处读到我们可以动态创建一个表单元素并将句柄提供给浏览器,而不是让应用程序处理 blob 并将其存储在内存中。所以我尝试了

post_to_url(path, params, method) {
        method = method || "post";

        var form = document.createElement("form");
        form.setAttribute("method", method);
        form.setAttribute("action", path);

        for (var key in params) {
            if (params.hasOwnProperty(key)) {
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden");
                hiddenField.setAttribute("token", key);
                hiddenField.setAttribute("value", params[key]);

                form.appendChild(hiddenField);
            }
        }
        document.body.appendChild(form);
        form.submit();
    }

这似乎不起作用,页面总是重定向到某个错误页面。所以我的问题是,如何在不挂起浏览器的情况下下载一个大文件。请帮忙

也许只是生成 link 以在 post 上下载文件:

this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
            .subscribe((data) => {

              let link = data.body; // //http://path/to/file;
              window.open(link);

              // or
            var link = document.createElement('a');
            link.href = link 
            link.click();
            });

问题是我在做

hiddenField.setAttribute("token", key);

而不是

hiddenField.setAttribute("name", key);

改名解决了我的问题