Java – problem downloading file using content disposition
I want my program to have a pop-up window to save as a window option before the file starts downloading, but when I run my servlet, it will automatically start downloading the file What did I miss here?
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { ServletOutputStream outputStream = response.getOutputStream(); FileInputStream fis=new FileInputStream("E:/sound.mp3"); response.setContentLength(fis.available()); response.setContentType("audio/basic"); response.addheader("content-disposition","attachment;filename=abc.mp3"); while(true){ int read = fis.read(); if(read==-1)break; outputStream.write(read); } fis.close(); }
Solution
Your program is not desktop / stand-alone because it is a servlet running on the server When you run it in eclipse by right clicking and running it as – > on the server, eclipse actually opens a web page to display the results Therefore, your application is now a web application, and eclipse (or the page it opens) is the client The client is saving the information you sent, not your program Got it?
The content disposition header is only used for file names that are recommended for download The browser settings define whether the save as window will open You can't control it
For example, in Google Chrome, in settings / advanced settings / download, you can choose to ask where to save each file before downloading Only when this option is selected will it open the required dialog box Otherwise, it saves it in the default location (also defined in browser settings) Similar options exist in all browsers
Also note that depending on the content type title, the browser will try to display the content instead of downloading it For example, the browser will try to display text and HTML However, you can force the download by setting the header to a non displayable type:
response. Setcontenttype ("application / octet stream");
If you don't want to create a web application: because your program runs on the server, it just sends information and completes The client program decides how to handle it In your current case, the client is the browser (or eclipse opens the browser page) Titles such as the content - disposition header are targeted at browsers If you want to create your own client (swing client, Android application, iPhone application) instead of a browser, the client will receive information from the server and decide how to process it (display it or save it in any client) and even ignore the HTTP header