I want my program to have a pop-up save as window option before file start downloading, however when I run my servlet it automatically starts downloading the file. What am I missing 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();
}
Your program is NOT desktop/standalone, since it is a servlet running on a server. When you run it in Eclipse by right clicking and run as -> run on server, Eclipse actually opens a web page to display the results. Therefore, your program 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 there only to suggest the file name of the download. The browser settings define if it will open a Save As Window or not. You cannot control that.
For example, in Google Chrome, in Setting/Advanced Setting/Downloads, there is the option Ask where to save each file before downloading. Only if this option is selected it will open the dialog you want. Otherwise it will save it in a default location (also defined in the browser settings). Similar options exist for all browsers.
Please also note that, depending on the content-type header, the browser will try to display the content, and not download it. For example, the browser will try to display texts and html. But then you can force the download by setting the header to a non-displayable type:
response.setContentType("application/octet-stream");
In case you don't want to create a Web app: Since your program runs on a server, it simply sends the information and is done. It is the client program who decides what to do with it. In your present case the client is a browser (or Eclipse opening a browser page). Headers such as the content-disposition header are aimed at browsers. If you are to create your own client (Swing client, Android app, iPhone app) which is NOT a browser, then the client will receive the information from the server and decide what to do with it (display it, or save it in any way), even ignoring the HTTP headers.
Try looking here: http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm
take out the main statement in their code and put run(new FileChooserTest(), 250, 110); in your own code. If I were doing it, I would make an int named saveStatus and 3 finals that equal 0, 1, and 2 named waiting, save, and cancel. Then I would do a while loop in your other programming to see if saveStatus was equal to waiting to pause your program (but not the dialog). Afterwards, I would make an if statement to see if saveStatus was equal to save. If so, download it, and if not, don't. Simple as that.
Your problem is the Mime-Type. Some types (especially those where a specific handler is known) will be downloaded directly by most browsers. It does help a bit to use application/binary, but even then some browsers might be configured to download it or interpret the file name extension in the disposition handler.
I think most solutions use javascript on the page before the download link.
You have to implement the dialog manually, e.g. (http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html). After user selecting the file, you will be able to start the http request download (to your servlet) and save the file to the desired path.
Related
Introduction
I am making a proxy server in java. Whenever the user enters an unknown host (URL) in the browser, the proxy server handles UnknownHostException by executing the code below:
try {
Process p=Runtime.getRuntime().exec("cmd /c start http://www.mysite.com/unknownhosterror.htm");
}
catch(IOException io) {
System.out.println("Error");
}
What these lines of code do is to display an html file containing "This page could
not be displayed." whenever the user entered a non-existing URL.
Problem
The code above opens a new tab and displays the content of www.mysite.com/unknownhosterror.htm. What I want is to redirect to it.
For example, I wrote www.nosuchsite.com in the URL bar. Suppose there is no such site, it will automatically redirect to www.mysite.com/unknownhosterror.htm and display "This page could not be displayed.".
How can I do this?
EDIT NOTE: I do not use Servlet.
I may be misunderstanding what you mean but if you indeed have a proxy server, they you should be able to issue a 301 redirect back to the browser when the proxy server detects the UnknownHostException.
In the response to the browser, you need to add something like the following lines to the header of your response:
HTTP/1.1 301 Moved Permanently
Location: http://www.mysite.com/unknownhosterror.htm
How to add that to your headers depends highly on how you are handling the requests. If you show a little bit of your proxy handler code, I can provide more information.
I have an applet which is partly designed to (only) read in text files and make stuff based on that. in my applet, this is what I have as the "read" method which reads in files:
public void read (String file1) throws IOException
{
str.removeAllElements (); // str is a global vector
BufferedReader dia = new BufferedReader (new FileReader (file1));
for (;;)
{
strc = dia.readLine ();
if (strc == null)
break;
str.add (strc);
}
}
this works fine when I'm running it through the JVM, but when I take it online the files that I want to access are not accessible even though they are hosted on the same server and folder.
HTML for my applet looks like this:
<applet
codebase = "[the url that hosts my class and text files]"
code = "[my class file].class"
width = ###
height = ###>
</applet>
The specific error I'm getting is:
AccessControlException
access denied ("java.io.FilePermission" "dial1.txt" "read")
So if anyone could help, that would be awesome!
I suspect the real problem here is using a java.io.File. Put server/client aside for the moment and a sand-boxed applet cannot establish a File - at all. But to extend that slightly, a trusted applet can establish a File - but only one that points to files on the local drives of the client machine. A File can never point back to the server, they just don't work that way.
So that leads to. The proper way for an applet to access resources is by URL. Java uses URLs a great deal, even for accessing classes in Jars.
A sand-boxed applet can establish an URL pointing back to the server from which it was deployed.
As to how to form that URL. The URL can be formed relative to the code base (the location of the Jars/classes) or document base (the location of the HTML).
Applets run inside the web browser. Hence, on the computer of the user who downloads your applet. So even if the files you are looking for exist on the computer of the user you won't be able to read them because you don't have file system access to people surfing the internet. Read your local file on server-side. So in your case, you probably need a servlet instead of an applet.
Folks, here is the situation:
confirmed that the xlsx file is good on the disc.
I copied the file from server and can open without problems.
using FileInputStream and BufferedInputStream to handle the client side download function.
The download function i mean user can download the file by clicking a hyperlink, and a servelet call was made to the java class which uses FileInputStream and BufferedInputStream
Mime type was set correctly as application/vnd.openxmlformats-officedocument.spreadsheetml.shee
After download the file successfully, it will give a "converted failed" error while trying to use office 2003 to open this xlsx file.
any thoughts?
Thanks!
There are bytes which didn't belong in the HTTP response body or were simply missing there.
It's impossible to point out the actual root cause based on the information given as far. You have to check if the right bytes were written from local disk file system to the HTTP response body.
HI can anybody tell me how to create a file and write on it on the URl.
Actually I am using an applet and from theat I want to create a file on
getCodebase(); so can any body tell me how can I do it
I have tried
URL url = new URL(/*url by codebase and the directory with file name*/);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStream out = connection.getOutputStream();
but it not worked
Please help me
Actually I am using an applet and from theat I want to create a file on getCodebase();
Well that wouldn't be very secure if you could do that, would it?
I think the route you want to take is to configure your HTTP server to handle PUT requests, and then form a PUT in Java. That is described here:
How to send PUT, DELETE HTTP request in HttpURLConnection?
However, your applet probably needs elevated permissions (in other words, a signed applet that operates outside of the normal sandbox). I'm not sure about that though; some connections are allowed back to the host so you might be OK.
I'm following Scott Davis' tutorials on developing grails apps, but whenever i try to run my app (or indeed his source code) i get "Firefox has detected that the server is redirecting the request for this address in a way that will never complete." Safari gives a similar error message as does Opera.
As i've tested the original authors source code which gives the same error i'm fairly confident it's nothing to do with the code.
Is this a problem with the web server on my machine? I use Mac OS Snow Leopard so i'm assuming it's apache that's generating this error.
Edit: Seems Grails as standard uses Jetty, so probably not Apache that is causing the problem. However also tested the app on Glassfish and i get the same error.
Anyone know what i can do to fix this?
Cheers
It depends on the code and Apache configuration you are using. I assume that the web server sends cyclic HTTP redirections, eg. from /root/ to /root (without the slash) and vice versa. This causes a redirection infinite loop.
Check your configuration on conditions that cause a HTTP redirect. For example, Apache automatically adds slashes to directory URLs in standard configuration (like the /root/ example above). I don't know Grails, so I cannot give you a hint on how URLs are processed within the app.
You can also use manual HTTP requests for debugging to see whats going on behind the scenes, using telnet on a terminal:
$ telnet localhost 80
GET / HTTP/1.0
I guess the response will be something like that:
HTTP/1.0 302 Found
Location: XXX
...
Now do a second request on the URL passed in the Location header and so on.
I was getting the same error a little while ago, heres how I fixed:
Try the same page on a different internet setup (it could be your ISP)
Open up Safari, Firefox or whatever your using and empty the cache and delete ALL your cookies
Reboot your computer and try again
It may work now, but if it doesn't:
open up Firefox and type 'about:config' (without the quotes) into the URL bar
You will get some little warning, just press OK
Type 'redirect' into the Filter box
You should see a listing for 'network.http.redirection-limit'
Double click the listing and type a large number (anything above 50 and lower than 200)
Press OK, quit and re-open FireFox
Basically all that does is make FireFox's tolerance for redirect loops higher which should fix your problem - but usually, just borrowing someone else's internet connection fixes it
Hope that all helps =)
Just carefully check your URLMappings configuration:
YOUR_APP/grails-app/conf/UrlMappings.groovy
Common case:
You configured request to be handled like this:
"/anything" (controller:"someController")
So without action, request will be handled by default one, "index". "index" action usually redirects to "list", and "list", in some cases redirect back to "index"
There is your loop.
Good luck