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

后端 未结 8 2578
忘掉有多难
忘掉有多难 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条回答
  •  旧时难觅i
    2020-12-15 09:51

    public static boolean uploadImage(final byte[] imageData, String filename ,String message) throws Exception{
    
        String responseString = null;       
    
        PostMethod method;
    
        String auth_token = Preference.getAuthToken(mContext);
    
    
        method = new PostMethod("http://10.0.2.20/"+ "upload_image/" +Config.getApiVersion()
               + "/"     +auth_token); 
    
                org.apache.commons.httpclient.HttpClient client = new              
                                            org.apache.commons.httpclient.HttpClient();
                client.getHttpConnectionManager().getParams().setConnectionTimeout(
                                100000);
    
                FilePart photo = new FilePart("icon", 
                                                      new ByteArrayPartSource( filename, imageData));
    
                photo.setContentType("image/png");
                photo.setCharSet(null);
                String s    =   new String(imageData);
               Part[] parts = {
                                new StringPart("message_text", message),
                                new StringPart("template_id","1"),
                                photo
                                };
    
                method.setRequestEntity(new 
                                              MultipartRequestEntity(parts,     method.getParams()));
                client.executeMethod(method);
                responseString = method.getResponseBodyAsString();
                method.releaseConnection();
    
                Log.e("httpPost", "Response status: " + responseString);
    
        if (responseString.equals("SUCCESS")) {
                return true;
        } else {
                return false;
        }
    } 
    

    You can also see an Example on my blog Here

提交回复
热议问题