Search code examples
androidfile-uploadmimemultipart

Image gets distorted sometime while uploading


I am using MIME multipart for uploading images to server. Sometime image get distorted. How to resolve this issue? Note: Distorted means, some pixels are lost. I am using following code for uploading:

File file = new File(filePath[0]);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("serverurl");

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("Content-Type",new StringBody("multipart/form-data;charset=utf-8"));
entity.addPart("Content-Length", new StringBody(String.valueOf(file.length())));
entity.addPart("UploadContentPostD", new FileBody(file));                   
entity.addPart("DocumentName", new StringBody(file.getName()));

httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,localContext);
BufferedReader reader = new BufferedReader(new    InputStreamReader(response.getEntity().getContent(), "UTF-8"));

Distorted image is: enter image description here


Solution

  • I use Apache Commons for upload and here is my upload code which works perfectly every time...

    public Integer uploadByteArray(String remoteFilename, byte[] bitmapdata){       
            HttpClient client = new HttpClient();
            PostMethod filePost = new PostMethod( URL_PATH);
    
            Integer ret = null;
    
            try {           
                Part[] parts = new Part[2];
                parts[0] = new StringPart("file_name" ,remoteFilename);
    
                ByteArrayPartSource ps = new ByteArrayPartSource("file", bitmapdata);
                parts[1] = new FilePart("file", ps);
    
                filePost.setRequestEntity(new MultipartRequestEntity(parts,
                        filePost.getParams()));
    
            } catch (Exception e) {
                Log.d(TAG, e.toString());
            }
    
            try {
                ret = client.executeMethod(filePost);
                Log.d(TAG, "statusCode>>>" + ret);
                if(ret != 200){
                    Log.d(TAG, "Error:" + ret + " from server. Please try again later.");
                }else{
                    responseBody = filePost.getResponseBodyAsString();
                    Log.d(TAG, filePost.getResponseBodyAsString());
                }
            } catch (Exception e) {
                Log.d(TAG, e.toString());
            }
    
            filePost.releaseConnection();
    
            return ret;
        }
    

    If you continue to see your problem recurring, I would use MD5 on the file you get on the server and send that value back in the response and compare it to a local MD5 of the file you've sent up. If they're not the same, you know something went wrong.