In web development, it is often necessary to develop the "download" module, the following gives a simple example.
On the server side, use Java development:
@RequestMapping (value = "download.html", method = requestmethod.get) public void Downlo AD (String ResourceID, httpservletrequest request, httpservletresponse response) {Response.setcontenttype ("charset=
UTF-8 ");
File File = new file (path); Response.setheader ("Content-disposition", "attachment;
Filename=a ");
Bufferedinputstream bis = null;
Bufferedoutputstream BOS = NULL;
OutputStream fos = null;
InputStream FIS = null;
try {fis = new FileInputStream (File.getabsolutepath ());
bis = new Bufferedinputstream (FIS);
FOS = Response.getoutputstream ();
BOS = new Bufferedoutputstream (FOS);
int bytesread = 0;
byte[] buffer = new BYTE[5 * 1024];
while ((bytesread = bis.read (buffer))!=-1) {bos.write (buffer, 0, bytesread);
} bos.flush ();
}catch (e e) {}finally {try {bis.close ();
Bos.close ();
Fos.close ();
Fis.close ();
catch (IOException e) {e.printstacktrace (); }
}
}
When we request this address at the front end, the server first finds the file, sets the response header, and then outputs the stream to the browser end.
When the browser finds that the body of the response in the header is a stream file, the saved as window is automatically invoked, allowing the user to save the download.
The key here is content-disposition this header property, Content-disposition is an extension of the MIME protocol that indicates how to have the client display the file for the attachment.
It can be set to two values:
Inline//Online open
Attachment//As Attachment download
The value we set here is attachment, so it can be identified as an attachment and downloaded.
It says how to write the server side, and here's how the front end is requested.
There are three ways to front end requests:
1.Form
<form action= ' download.html ' method= ' post ' >
<input type= ' Submit '/>
</form>
2.iframe
var iframe = "<iframe style= ' display:none ' src= ' download.html ' ></iframe>"
body.append (IFRAME);
When the IFRAME is append into the body, the download link is automatically requested.
3.open
window.open ("download.html");