Skip to content

Instantly share code, notes, and snippets.

@vpodlesnyak
Created April 2, 2014 08:54
Show Gist options
  • Save vpodlesnyak/9930423 to your computer and use it in GitHub Desktop.
Save vpodlesnyak/9930423 to your computer and use it in GitHub Desktop.
Multipart POST file upload
public static void uploadFile(String urlString, Map<String, String> params, String fileName, InputStream fileInputStream) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
HttpURLConnection conn;
try {
// ------------------ CLIENT REQUEST
Log.e(Tag, "Inside second Method");
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
for (Entry<String, String> e : params.entrySet()) {
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\""+e.getKey()+"\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(e.getValue());
dos.writeBytes(lineEnd);
}
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: post-data; name=\"catlog\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.e(Tag, "Headers are written");
// create a buffer of maximum size
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1000;
// int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bytesAvailable];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
while (bytesRead > 0) {
dos.write(buffer, 0, bytesAvailable);
bytesAvailable = fileInputStream.available();
bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e(Tag, "File is written");
fileInputStream.close();
dos.flush();
dos.close();
int code = conn.getResponseCode();
} catch (MalformedURLException ex) {
Log.e(Tag, "error: " + ex.getMessage(), ex);
} catch (IOException ioe) {
Log.e(Tag, "error: " + ioe.getMessage(), ioe);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment