I have a requirement to download multiple files using POST request. So I am using form submit to get this done.
I have followed two approaches to accomplish this.
Create a Form. Fill input details with payload data. Then set the target of the Form to
_selfthen manually submit the Form. But I see few problems with this approach. Like, When payload is incorrect or Server has download API problems the current page will be redirected to 404 page.
var method = "POST"; var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", "https://some-url"); appendFormData(form, options.data.items); document.body.appendChild(form); form.submit(); document.body.removeChild(form);
2) Second approach is similar to the first one, except that I am creating an iframe, appending it to DOM and providing iframe as the target for Form. This works but the problem is, I am not sure when to remove the iFrame from the DOM.
var method = "POST"; var iframe = document.createElement("iframe"); iframe.setAttribute("name", "hidden-frame"); iframe.style.display = "none"; document.body.appendChild(iframe); var iDocument = iframe.contentWindow.document; var form = iDocument.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", "https://some-url"); form.setAttribute("target", "hidden-frame"); appendFormData(form, options.data.items); iDocument.body.appendChild(form); form.submit();
Can you please suggest ways to improve the above solution or suggest if there are any better approach to accomplish the same.