I am working on a project where I need to upload files to a remote server. I also need to send some other POST Parameters along with the file. Following is the code on the android side:
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(UPLOAD_URL);
co = (HttpURLCoection) url.openCoection();
co.setDoInput(true);
co.setDoOutput(true);
co.setUseCaches(false);
co.setRequestMethod("POST");
co.setRequestProperty("Coection", "Keep-Alive");
co.setRequestProperty("ENCTYPE", "multipart/form-data");
co.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
co.setRequestProperty("myFile", fileName);
dos = new DataOutputStream(co.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name="myFile";filename="" + fileName + """ + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.i("Huzza", "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = co.getResponseCode();
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(co.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException ioex) {
}
retu sb.toString();
}else {
retu "Could not upload";
}
The file is successfully uploaded through this code. I need to know how do I send other POST Parameters along with it. Thanks.
