Skip to content

Instantly share code, notes, and snippets.

@mr5z
Created October 6, 2015 08:51
Show Gist options
  • Save mr5z/a91235bd1bb8d477d770 to your computer and use it in GitHub Desktop.
Save mr5z/a91235bd1bb8d477d770 to your computer and use it in GitHub Desktop.
upload image in localhost:8080
private int uploadImage(File imageFile) {
int serverResponseCode = -1;
String fileName = imageFile.getName();
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
HttpURLConnection conn = null;
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(imageFile);
URL url = new URL(Settings.URL_BASE + Settings.URL_UPLOAD_IMAGE);
// Open a HTTP connection to the URL
int timeout = 20 * 1000; // 20 seconds
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(timeout);
conn.setConnectTimeout(timeout);
conn.setRequestMethod("POST");
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", "\"" + fileName + "\"");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;" +
"name=image-file;" +
"filename="+ fileName + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Debug.log("HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if( serverResponseCode == HttpURLConnection.HTTP_OK ) {
Debug.log("Success!");
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
}
catch (Exception e) {
Debug.log("Exception : " + e.getMessage());
}
finally {
if ( conn != null ) {
conn.disconnect();
}
}
return serverResponseCode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment