How can my web application written in Java open a file on the client side?
I have written a Java web application that copies a file from the server to the client's machine. 开发者_开发知识库The user should be able to open that file on the client side by a click. In my java code I use :
Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL "+ FilePath);
Where the FilePath has the client's IP address. This command opens the file but the problem is that the file opens on the server side NOT the client. Does anyone has an idea how I can do this?
Thanks,
The code of a Java web application runs at the server machine, produces HTML/CSS/JS and sends it to the webbrowser which runs at the client machine. Java code doesn't run at the client machine, let alone have any direct access to the client environment.
If you want to execute Java code on the client machine, you need to do it inside a signed(!) applet which you then embed in your web page which in turn get downloaded to the client machine and executed over there. Then you can just use Desktop#open()
instead of that ugly and platform-specific rundll call which ain't going to work on Linux/Mac clients.
Desktop.getDesktop().open(new File("/path/to/foo.txt")); // Opens notepad on Windows.
See also:
- Java tutorial - Applets
A Web Server can not access the client's computer. Imagine if Google (or any other site) could just start programs on your machine when you visit their site!
That said, if you need to make it happen, you will have to use some signed browser extension.
I did things like this many years ago with signed Java applets.
Basically, you create a Java Applet, sign it with a certificate and request certain permissions from the client. The client user allows (or denies) the permission and then the process is started.
Here are some ancient resources:
- Signed Applets
- How to Sign Applets Using RSA Certificates
- Quick Tour of Controlling Applets
Other technologies that can access the client's computer if permissions are granted include Microsoft's ActiveX and Adobe's Flash / Flex / Air, however I don't have any experience in these technologies that I could share.
If the snippet of code that you've provided is part of a servlet, then it will execute on the server.
One way to open the file on the client side would be to generate a hyperlink that the client clicks, which should then be received by your web-app and result in the file being streamed back to the clients browser with the correct MIME type in the http header.
The user may be presented with a file open dialog and asked to select the application to use to open the file, but as long as the application is installed on the client, then the MIME types should present the correct application as a default.
精彩评论