Uploading image to server in Multipart along with JSON data in Android

后端 未结 8 2547
忘掉有多难
忘掉有多难 2020-12-15 09:36

I am trying to upload an image to a server along with some JSON data that is collected from a form.

The server has authentication.

METHOD: post

HEAD         


        
8条回答
  •  伪装坚强ぢ
    2020-12-15 09:50

    Try this Code it's easy

    public String postAsync(String url, String action, JSONObject jsonObject, String fileUri) throws JSONException {
            String result = "";
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                entityBuilder.setMode(HttpMultipartMode.STRICT);
                File file = new File(fileUri);
                entityBuilder.addPart("file", new FileBody(file));
                entityBuilder.addTextBody(DMConstant.ACTION_JSON, action);
                entityBuilder.addTextBody(DMConstant.DATA_JSON, jsonObject.toString(), ContentType.create("application/json", Consts.UTF_8));
                HttpEntity entity = entityBuilder.build();
                httpPost.setEntity(entity);
                HttpResponse httpResponse = httpClient.execute(httpPost);
                InputStream inputStream = httpResponse.getEntity().getContent();
                if (inputStream != null) {
                    result = dmUtils.convertStreamToString(inputStream);
                } else {
                    Log.i("Input Stream is Null", "Input Stream is Null");
                }
            } catch (UnsupportedEncodingException e) {
                Log.e("Unsupported Encoding", e.getMessage());
            } catch (ClientProtocolException e) {
                Log.e("Client Protocol", e.getMessage());
            } catch (IOException e) {
                Log.e("IOException", e.getMessage());
            }
            Log.i("JSON Object as Response", result);
            return result;
        }

    ........
    
    JSONObject urlObject = new JSONObject();
                            urlObject.put("userName", "user name");
                            urlObject.put("email_id", "äbc@gmail.com");
                            urlObject.put("user_pass", "123456");
    
    
    postAsync(URL, "php function name", urlObject, imageFile); 

提交回复
热议问题