Upload file using Java Swing and PHP


Java Swing File upload with Php on the server

You can upload a file through your swing application to a web server supporting PHP (Apache).

You can use jakarta HttpClient library

Following is the code at the client side

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
 
public class UploadFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
 
HttpPost httppost = new HttpPost("http://localhost:9001/upload.php");
File file = new File("c:/my.jpg");
 
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
 
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
 
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
 
httpclient.getConnectionManager().shutdown();
}
}


For Server side code in PHP you may use

1
<!--?php  if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {    echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";   move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']); }  else  {    echo "Possible file upload attack: ";   echo "filename '". $_FILES['userfile']['tmp_name'] . "'."; print_r($_FILES); } ?-->