Home > Article > Web Front-end > Introduction to the method of implementing multiple tasks at one download using javascript
This article brings you a detailed explanation of PHP synergy implementation (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Real experience
Recent development projects require file downloading. It’s quite simple when you think about it. I’ve done it before. The background provides a download interface and the front-end uses window. .location.href
will do. However, during development, I found that some files have attached files. Clicking the Download button requires downloading two files, and the compressed package cannot be used. Come to think of it, it's quite simple. Just click Download and send two download requests and you're done.
Just do it, and it was written in three strokes, five divided by two. When I clicked to download, I was stunned. The first request was automatically cancelled, and suddenly 10,000 grass mud horses rushed past ( Because it is a foreign server, the download is slow and the first request is Cancelled), which means that quickly clicking different download buttons will have the same problem. This is not good, and then I started my own download exploration journey.
a tag & location.hrefWe know that if the a tag and href point to a download link, it is equivalent to downloading a file. It is still ok for single file downloads, but click a few quick There is a download button. Some downloads will be Canceled. This is not acceptable. Continue to Baidu.
Previous code:
const download = (url)=>{ window.location.href = url; }window.open
We know that window.open can open a new window, so is it possible to download it? I was so excited that I quickly tried it I tried it and it was indeed possible to download, but a new window would quickly open and close. The experience was very bad, so I gave up decisively.
iframeIt suddenly occurred to me that iframe can also send requests to the server. I was so excited that I quickly tried it again. Wow, it can be downloaded, and there is no sense of violation. I posted the code.
export const downloadFile = (url) => { const iframe = document.createElement("iframe"); iframe.style.display = "none"; // 防止影响页面 iframe.style.height = 0; // 防止影响页面 iframe.src = url; document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求 // 5分钟之后删除(onload方法对于下载链接不起作用,就先抠脚一下吧) setTimeout(()=>{ iframe.remove(); }, 5 * 60 * 1000); }
ps: iframes will not affect each other and can be downloaded continuously!
Other solutionsOf course there are other ways, such as Form download, binary stream download, etc., there are Sora friends, please do your own research!
The above is the detailed content of Introduction to the method of implementing multiple tasks at one download using javascript. For more information, please follow other related articles on the PHP Chinese website!