Today, I encountered a problem in the project. Originally, the href of Tag a contains the address for downloading the file, but the click is invalid, it was found that the default behavior of all the tags was blocked in the js script, and the click event of the tag called e. preventDefault (); so in this summary.
Two common methods for file download
- Using the tag, href directs directly to the file address of the server.
<A id = "download" href = "upload.txt"> </a> download
2. Download files through the backend service
<A id = "download" href = "/service/upload? Id = 123 "> </a> Download
In the first case, what should I do if the default behavior of Tag a is blocked on this page?
We usually think of window. open Method: Add an event to the download button and call window. open ("file address"); yes, it does. However, an empty window will be opened after you click it. How can this problem be solved?
Windows is found on w3cSchool. the second parameter in open (URL, name, features, replace) is an optional string, which is a list of features separated by commas (,), including numbers, letters, and underscores, this character declares the name of the new window. This name can be used as the value of the target attribute for marking <a> and <form>. If this parameter specifies an existing window, the open () method will not create a new window, but will only return a reference to the specified window. Then you can add an iframe to the current page.
<Iframe name = "downloadWnd" style = "height: 0; width: 0"> </iframe>
$ ("# Download"). click (function (e ){
Window. open ("address of the file to be downloaded", "downloadWnd ");
});
In this way, I think of another application scenario: page files are not refresh, and files are generally uploaded through form.
<Iframe name = "uploadWnd" style = "height: 0; width: 0"> </iframe>
<Form action = "/service/upload/" target = "uploadWnd" enctype = "multipart/form-data">
<Input name = "file" type = "file"/>
<Input type = "submit"/>
</Form>
File Download