19Upload an image using Java + PHP

Upload an image using Java + PHP

Whilst working on a recent project I needed a way of transferring images (screenshots to be specific) from the client machine to a web server hosted in the cloud. My choice of platform was Java on the client machine and then PHP on the server side to recieve and process the upload.

So basically I needed to upload an image to a web server using Java and PHP. Reading and writing simple data to and from a web server with Java is pretty easy really but when it comes to transferring files things get that little bit tougher. This is because when uploading files the content type of the HTTP request changes from plain text to multipart making it trickier. You could either write a whole load of extra code to deal with this or you could simply send the data over as plain text and then just let PHP deal with it. Here’s how it’s done.

The Java

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
42
43
44
45
46
47
48
49
// Setup vars
HttpURLConnection httpUrlConnection;
OutputStream outputStream;
BufferedInputStream fileInputStream;
BufferedReader serverReader;
int totalBytes;
int bytesTrasferred;
String response = "";
String serverResponse = "";
String localFileName = "mypicture.jpg";
 
// Establish a connection
httpUrlConnection=(HttpURLConnection)new URL("http://www.example.com/upload.php").openConnection();
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestMethod("POST");
outputStream = httpUrlConnection.getOutputStream();
 
// Buffered input stream
fileInputStream = new BufferedInputStream(new FileInputStream(localFileName));
 
// Get the size of the image
totalBytes = fileInputStream.available();
 
// Loop through the files data
for(int i=0; i < totalBytes; i++)
{
	// Write the data to the output stream
	outputStream.write(fileInputStream.read());
	bytesTrasferred = i + 1;
}
 
// Close the output stream
outputStream.close();
 
// New reader to get server response
serverReader = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
 
// Read the servers response
serverResponse = "";
while((response = serverReader.readLine()) != null)
{
	serverResponse = serverResponse + response;
}
 
// Close the buffered reader
serverReader.close();
 
// Close the file input stream
fileInputStream.close();

The PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// Config
$uploadBase = "img/";
$uploadFilename = time() . ".jpg";
$uploadPath = $uploadBase . $uploadFilename;
 
// Upload directory
if(!is_dir($uploadBase))
	mkdir($uploadBase);
 
// Grab the data
$incomingData = file_get_contents('php://input');
 
// Valid data?
if(!$incomingData)
	die("No input data");
 
// Write to disk
$fh = fopen($uploadPath, 'w') or die("Error opening file");
fwrite($fh, $incomingData) or die("Error writing to file");
fclose($fh) or die("Error closing file");
 
echo "Success";

And that’s all there is. By placing the PHP script above onto a suitable web server and then executing the Java code you’ll be able to quite easily and painlessly transfer images (or any other file types) from the desktop client to the web.