preface
How to download files on the front end? With the development of front-end technology, more and more front-end requirements will appear such as the need to download files.
Looking at the nugget many people in the recent continuous sharing of relevant articles, I summed up my own experience, according to different situations, summed up a general front-end file download, if you do not understand this aspect or do not have any plan, then this article will give you a very good inspiration.
Solution 1: Native commit, the back end returns the file stream
In this way, form. Submit is directly submitted to the back end, and the back end returns the files generated by the file stream. After successful processing, the back end will directly return to the page, and the browser will organize and open its own saving and downloading file mechanism.
Advantages: No compatibility issues with the traditional way
Disadvantages: No time for the backend to process the process, no interaction based on callback functions and progress hints
// The backend reference codereturn File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", HttpUtility.UrlEncode("Consulting record export. XLS", Encoding.GetEncoding("UTF-8"))); // Reference codefunction exportRecord() {
var $form = $("<form>"); // Define a form$form.hide().attr({target:' ',method:'post'.'action':'/xxx'});
var $input = $("<input>");
$input.attr({"type":"hidden"."name":'req'}).val(req);
$form.append($input).appendTo($("body")).submit().remove();
}
Copy the code
Solution 2: Ajax submission, the back end returns the online file address
To submit a request using Ajax or the newly generated Axios, the back end will return an online file address, which the front end can open with the native window.open to download. You can also set the href and download attributes through the A tag, and automatically click to achieve the download function. As for the compatibility problem, you can determine whether the Download attribute exists to compensate.
Advantages: can get its return time, can do interaction
Disadvantages: a large number of intermediate temporary files are stored online, which can be optimized by setting a time limit. In addition, user privacy issues can be implemented by token authentication mechanisms.
// Reference scheme $.ajax({type: "post",
url: "/xxx",
data: data,
success: function (res) {
tool.loadingend();
if(res.status){// window.open or a tag to download var isSupportDownload ='download' in document.createElement('a');
if(isSupportDownload){
var $a = $("<a>");$a.attr({href:res.url,download:'filename'}).hide().appendTo($("body"))[0].click();
}else{
window.open(res.url)
}
}else{ tool.tip(res.Message); }}})Copy the code
- A Tag Download attribute
- Solution 2: Supplementary solution: use the form form to submit and download the file (Ajax cannot directly handle the returned file type), which is used to solve the situation that window.open solution is blocked by the browser.
let $form = $("<form>");$form.attr({method:"get",action:res.Message}).hide();
let queryStr = res.Message.split("?") [1];let queryObj = qs.parse(queryStr) ;
$("body").append($form);
for(let p in queryObj){
let $input= $("<input type='hidden'>");$input.attr({"name":p,value:queryObj[p]}).appendTo($form);
}
$form.submit().remove();
Copy the code
Solution 3: The front-end uses the Download module to download
- Download Module download
- Jquery – download the plugin
Support scenarios: Compared to the above solutions, this module provides a more complete solution, rather than being limited to one solution, and is highly used. In the source code, we can see that the module is fully compatible with browsers and whether the corresponding properties are supported. The corresponding download file scheme includes the following types.
- Window.open (URL) Opens a file address
- In the iframe framework, set the SRC attribute, download files through the iframe, and support file addresses
- Use the form tag to set the address of the action file, and then download the file by submitting the form (binary).
Solution summary: for the conventional support file address download, compatibility is very good, and for the traditional file stream nature, through the form tag can also be simple support, can be said to be a very good solution. Of course, if you need a comprehensive solution, one or the other will do most of the work.
Scheme four: H5 freshmen scheme download
This I think zhang Xinxu big guy introduced quite a lot, should get started enough, not much to introduce. In addition to the Download attribute provided by the A tag, there is an HTML: bloB method introduced. In addition, you can use Base64 for images.
Portal: H5 new way to download files
Personal advice: Although the new technology is good, use it as appropriate, and there is no consideration for compatibility, and no mention of other file types such as forms, PDFS, large files, video and audio downloads, etc. So it’s not really recommended that you think about this as a very conventional solution.
Option 5: file-saver
Module address: npm.taobao.org/package/fil… Github hosting address: github.com/eligrey/Fil…
In the module introduction: detailed description of the browser support, and can support the download scope, save as the file type, and we go to use the basic knowledge to step on the mine, or suggest that we use mature module solution to solve the requirements related problems. Support can not retreat to the traditional solution, let the back end to provide a direct file address, to know that the back end has more mature technology rack package, for the front end or meng new uncertain solution, the back end has already had the answer.
Description: Our previous requirement was to download a table file. The previous solution was to use the back end to generate the file address, and then download it. The response content type of its return was set as Application /vnd.ms-excel (general type application/ JSON). At this time, the convention becomes that the back end generates a binary file stream according to the queried data. The advantage of this is that if it is not necessary, it can reduce the temporary storage of many files in Ali Cloud or other servers.
Think outside the box: In our company have faced similar requirements, according to my previous experience was originally a generated after returning to the back-end file address, but after the reply is due to adopt the load balance, this address to request may not request to the server, so the before and after the end of the before coordination scheme is on the ali cloud, Then through the setting of permission and time to ensure the temporary of the file, the user can also repeat the request to the database in similar requests, to re-generate the file, because the repeated data content will directly return to the file address that has been uploaded to Ali Cloud.
Source code parsing: In the source code, it is mainly required for the HTTP resonseType returned, and then processing for the returned address, which involves important code:
Var a = document.createElement();'a') a.href = blob // Trigger click event node.dispatchEvent(new MouseEvent('click')) / / reader parsing var reader = new FileReader () var url = reader. The result / / got address _global to parse the url | | _global. WebkitURL, Url.createobjecturl (blob) // Whether cross-domain support for CORS is supportedreturn xhr.status >= 200 && xhr.status <= 299
Copy the code
Filereader: developer.mozilla.org/zh-CN/docs/…
conclusion
To sum up, whether it is partial to the traditional scheme, or more compatible download according to the file address, or the new H5 WebAPI way have a better understanding, if you are interested in related knowledge or scheme to further research, It is suggested to conduct in-depth optimization and research for the related articles of the official API or the two modules that have been opened source.
I think it’s good, give me a zan and follow it, thanks for your support.