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