Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 (<a href="http://hc.apache.org/" rel="nofollow">http://hc.apache.org/</a>) contains pretty much everything you'll need to build HTTP-POST request in a quite simple way.</p> <p>Here is a method that will send a POST request with a file to a certain URL:</p> <pre><code>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 !"); } } </code></pre> <p>In order to complete the upload, you must have a php code that handle that POST request, here it is:</p> <pre><code>&lt;?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 } } ?&gt; </code></pre> <p>The URL object given to the Java method must point to the php code, like <a href="http://mysite.com/upload.php" rel="nofollow">http://mysite.com/upload.php</a> and can be build very simply from a String. The file can also be build from a String representing its path. </p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload