In web development, it is often necessary to develop a "download" module, the following is a simple example.
On the server side, use Java development:
@RequestMapping (value = "download.html", method = requestmethod.get) public void download (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 { &nBsp; 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 on the front end, the server first finds the file, sets the response header, and then outputs it to the browser side via the stream.
When the browser finds that the body of the response is a stream file in the header, the Save As window is automatically called to allow the user to save the download.
One of the keys here is content-disposition. This header property, Content-disposition, is an extension of the MIME protocol that indicates how the client displays the attached file.
It can be set to a value of two:
Inline//Open online
Attachment//As an accessory download
Here we set the value to attachment, so it can be identified as an attachment and downloaded.
It says how to write the server side, the following is how the front-end request.
Front-end requests are available in three ways:
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 to the body, the download link is automatically requested.
3.open
window.open ("download.html");
?