Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

File Upload from Desktop

800394May 16 2009 — edited May 17 2009
Hi,

How am I suppose to configure this to upload a file to my web server.
It prints the response code 200.
import java.io.File;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;


public class FileUpload {


    public FileUpload() {
        uploadFile();
    }

    void uploadFile() {
        try {


            File f = new File("fileToUpload.txt");
            

            PostMethod filePost = new PostMethod("http://mywebsite.mydomain.com/uf.php");
            Part[] parts = {
                new StringPart("name", "uploaded"),
                new StringPart("type", "file"),
                new FilePart(f.getName(), f)
            };
            filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
            HttpClient client = new HttpClient();
            int status = client.executeMethod(filePost);
            System.out.println(status);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
I'm not sure if I should post my PHP code which handles the upload since this is a java forum, but the PHP code is working fine if I upload a file from HTML-Form

Is there any alternative to this using just plain-java without any library?

Appreciated...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 14 2009
Added on May 16 2009
1 comment
121 views