Thanks to everyone who helped me.
Here is my success method, use post method to post two parameter(no, key) and image file to php server.
Hope can help other in need.
static String postUploadImageToPHPServer(String URL, String no, String key, String imgPath) {
String multipart_form_data = "multipart/form-data";
String twoHyphens = "--";
String boundary = "**********uploadimage**********";
String lineEnd = System.getProperty("line.separator");
try {
URL url = new URL(URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(120000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", multipart_form_data + "; boundary=" + boundary);
conn.connect();
DataOutputStream output = new DataOutputStream(conn.getOutputStream());
addImageContent(imgPath, output);
addNoFormField(no, output);
addKeyFormField(key, output);
output.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
output.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String oneLine;
while((oneLine = input.readLine()) != null) {
response.append(oneLine + lineEnd);
}
return response.toString();
} catch (Exception e) {
Log.e(TAG, "Error: " + e.getMessage());
return null;
}
}
Here method is how to add Image data.
private static void addImageContent(String _path, DataOutputStream _output) {
StringBuilder split = new StringBuilder();
split.append(twoHyphens + boundary + lineEnd);
split.append("Content-Disposition: form-data; name=\"" + "img" + "\"; filename=\"" + _path + "\"" + lineEnd);
split.append("Content-Type: " + "image/jpeg" + lineEnd);
split.append(lineEnd);
try {
Bitmap bitmap = BitmapFactory.decodeFile(_path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] imageBytes = baos.toByteArray();
_output.writeBytes(split.toString());
_output.write(imageBytes);
_output.writeBytes(lineEnd);
baos.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Here method is how to add text data, my addNoFormField
function is similar to addKeyFormField
function , just change name=\"your param\""
.
private static void addNoFormField(String _value, DataOutputStream _output) {
StringBuilder sb = new StringBuilder();
sb.append(twoHyphens + boundary + lineEnd);
sb.append("Content-Disposition: form-data; name=\"no\"" + lineEnd);
sb.append("Content-Type: application/json; charset=utf-8" + lineEnd);
sb.append(lineEnd);
sb.append(_value + lineEnd);
try {
_output.writeBytes(sb.toString());
} catch (Exception e) {
throw new RuntimeException(e);
}
}