0

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); } } 

2 Answers 2

0

I'm not sure you're doing this image uploading the correct way. Anyway, if your image upload works fine and if you have a problem in just sending those two parameters try adding these two parameters as another setRequestProperty.

Even the image upload also fails, check these: http://codesfor.in/how-to-upload-image-to-server-as-base64-encoded-string/comment-page-1/

Doing it JSON way, Sending base64 encoded image to server using HttpUrlConnection Android

Sign up to request clarification or add additional context in comments.

3 Comments

I update my code with the method which you provide, but I will get exceeded content-length limit of 566575 bytes
Have you set up set post_max_size in the Server-side code(PHP)?
Yes, server side set post_max_size = 8M
0

I was having the same problem when sending the image as string ,try to send it as a file through Multipart, try to use this function when you are making image request as postWebserviceCallForImage()

public String makeImageRequest(String url, String method, String image,List<NameValuePair> nameValuePairs) { //url to post the image,method 'post',image absolute path on the phone,'is' is inputstream try { json=""; MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); FileBody fbd=new FileBody(new File(image)); builder.addPart("my_file",fbd); //if you want to add string for (int index = 0; index < nameValuePairs.size(); index++) { builder.addPart(nameValuePairs.get(index).getName(),new StringBody(nameValuePairs.get(index).getValue(),ContentType.TEXT_PLAIN)); } HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 10000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 12000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); HttpEntity entity = builder.build(); httpPost.setEntity(entity); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return json; } 

In your asyn task call this function and I hope it will work and also dont forget to add this dependency to your gradle if not present:

implementation group: 'org.apache.httpcomponents', name: 'httpmime', version: '4.3.1' 

10 Comments

If I want to post string data and image data both for server, how can i do it
I did so by adding stringbody in the multipart data I am editing the post for your need
I have added namevaluepairs which is deprecated but you can replace with your own list , logic will remian the same, you need to add string body in multipart
I use your method, is not working. I try to use HttpURLConnection and MultipartEntityBuilder to post data, but it always get null. I update my code.
what do you get null
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.