Java WEB file download
Now we want to use the springMVC-based file download function.
Is not effective
Where is the problem?
After clicking the link, if it is a text file, it will be automatically opened instead of downloaded. If it is an image, it will be opened rather than downloaded.
So what should we do? After research, File Download is actually a request that uses response to download files.
The following is an example of object download in the form of a binary stream.
/*** Download file */@ RequestMapping (value = downLoadFile) public void downLoadFile (ReimFjInfo reimFjInfo, HttpServletRequest request, HttpServletResponse response) {log.info (download file ); // download the file as a binary stream. try {String fileName = new String (request. getParameter (fjName ). getBytes (ISO-8859-1), UTF-8); // get File information File downFile = new File (reimFjInfo. getFjUrl (); // get the object's byte input stream InputStream bufferStream = new BufferedInputStream (new FileInputStream (downFile); byte [] buffer = new byte [bufferStream. available ()]; bufferStream. read (buffer); bufferStream. close (); response. reset (); // set the response Header. You need to set the file name, which is the file name response displayed when downloading the file. setHeader (Content-disposition, attachment; filename = + new String (fileName. getBytes (gb2312), ISO8859-1); // when you are not sure about the file type, contentType uses the following form, which is. * (binary stream, unknown download file type) response. setContentType (application/octet-stream); // get the response byte output stream OutputStream out = new BufferedOutputStream (response. getOutputStream (); out. write (buffer); out. flush (); out. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}