Hi,
Many times, this question has been asked by so may people, yet, till now, no solution has been given. I am posting this query in the hope that, somebody might have already done it.
Problem Statement:
I have an http server to deploy my applet ( in fact a signed jar ) that will ask the client to upload files from his local machine. Is it possible using only output streams ( such as DataOutputStream, FileOutputStream) ? I have managed to write the file ( converted to bytes ) to the output stream, but not able to save it on the server as a file.
How do I do it? I'm pasting my code here :
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class FileUpload extends Applet implements ActionListener{
URL url;
File sourceFile, destFile;
FileInputStream fis;
URLConnection connection;
DataOutputStream dos;
FileOutputStream fos;
Button b;
byte[] buffer;
public void init(){
try{
url = getCodeBase();
connection = url.openConnection();
if (connection instanceof HttpURLConnection) {
System.out.println("This is HttpURLConnection");
((HttpURLConnection)connection).setRequestMethod("POST");
}
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "multipart/form-data");
dos = new DataOutputStream(connection.getOutputStream());
sourceFile = new File("D:\\myFile.txt"); //this has been hard coded for testing purpose
buffer = new byte[(int)sourceFile.length()];
}
catch(MalformedURLException mue){
System.out.println("MalformedURLException occured");
}
catch(IOException ie){
System.out.println("IOException occured");
}
b = new Button("Upload");
b.addActionListener(this);
add(b);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==b){
try{
dos.write(buffer,0,buffer.length);
System.out.println("Bytes written so far = " + dos.size());
dos.close();
}
catch(IOException ie){
System.out.println("IOException occurred during file transfer");
}
}
}
}
I tried using FileOutputStream too by appending the destination file name to the url, but it was not possible to convert the URL object to a File oblject.
And another thing, I don't want to use servlets/JSPs at the server. I know how to upload files from applets to servers using servlet/JSP at the server side, to handle the requests.
The http server for my application has limited functionality and is not a servlet engine.
Thanks in advance.
- JP