Question

Hi ive been having some trouble trying to transfer a png image to my webserver using java and php Ive tried using FTP but the software that Im scripting for blocks port 21 rendering it useless

I was directed to use form urlencoded data then use a POST request to get it im completely lost on this topic and could just use some direction apparently file and image hosting sites use the same method to transfer files and images from the users computer to their servers.

maybe just an explanation of whats going on might help so that I can grasp what exactly im trying to do with java and php

Any help would be much appreciated!

Was it helpful?

Solution

I've also been facing the same kind of problem a short time ago. After some researches, I found out that the HttpComponents library from Apache (http://hc.apache.org/) contains pretty much everything you'll need to build HTTP-POST request in a quite simple way.

Here is a method that will send a POST request with a file to a certain URL:

public static void upload(URL url, File file) throws IOException, URISyntaxException {
    HttpClient client = new DefaultHttpClient(); //The client object which will do the upload
    HttpPost httpPost = new HttpPost(url.toURI()); //The POST request to send

    FileBody fileB = new FileBody(file);

    MultipartEntity request = new MultipartEntity(); //The HTTP entity which will holds the different body parts, here the file
    request.addPart("file", fileB);

    httpPost.setEntity(request);
    HttpResponse response = client.execute(httpPost); //Once the upload is complete (successful or not), the client will return a response given by the server

    if(response.getStatusLine().getStatusCode()==200) { //If the code contained in this response equals 200, then the upload is successful (and ready to be processed by the php code)
        System.out.println("Upload successful !");
    }
}

In order to complete the upload, you must have a php code that handle that POST request, here it is:

<?php
$directory = 'Set here the directory you want the file to be uploaded to';
$filename = basename($_FILES['file']['name']);
if(strrchr($_FILES['file']['name'], '.')=='.png') {//Check if the actual file extension is PNG, otherwise this could lead to a big security breach
    if(move_uploaded_file($_FILES['file']['tmp_name'], $directory. $filename)) { //The file is transfered from its temp directory to the directory we want, and the function returns TRUE if successfull
        //Do what you want, SQL insert, logs, etc
    }
}
?>

The URL object given to the Java method must point to the php code, like http://mysite.com/upload.php and can be build very simply from a String. The file can also be build from a String representing its path.

I didn't take the time to test it properly, but it was build upon proper working solution, so I hope this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top