In web development, it is often necessary to develop the "download" module. Here is a simple example.
On the server side, use java to develop:
@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 { 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 through the stream.
If the browser finds in the header that the body of the response is a stream file, it will automatically call the Save As window to let the user save the download.
A key here is the header property of Content-Disposition. Content-Disposition is an extension of the MIME protocol to indicate how to let the client display the attachment file.
It can be set to two values:
inline //Open online
attachment //Download as attachment
Here we set the value to attachment, so it can be recognized as an attachment and downloaded.
The above talks about how to write to the server side, and the following talks about how to request the front-end.
There are three ways to request front-end:
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 an iframe is append to the body, the download link will be automatically requested.
3.open
window.open("download.html");