In web development, you often need to develop the "Download" module. The following describes how to download attachments using java and javascript. For more information, see web development, you often need to develop the "Download" module. The following is a simple example.
On the server side, use java for 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 at the front end, the server first finds out the file, sets the response header, and then outputs it to the browser through the stream.
When the browser finds in the header that the response body is a stream file, it will automatically call the Save As window for the user to save and download.
The key here is the Content-Disposition Header attribute. Content-Disposition is an extension of the MIME protocol, used to indicate how to make the client display the attachment file.
It can be set to two values:
Inline // Open Online
Attachment // download as an attachment
The value we set here is attachment, so it can be recognized as an attachment and downloaded.
The above section describes how to write data to the server and how to request data from the front end.
There are three frontend requests:
1. Form
2. iframe
var iframe = "" body.append(iframe);
When an iframe is appended to the body, the download link is automatically requested.
3. open
window.open("download.html");