上传时图像会被扭曲

时间:2011-12-14 14:07:03

标签: android file-upload mime multipart

我使用 MIME multipart 将图片上传到服务器。有时图像会变形。如何解决这个问题? 注意:失真意味着某些像素丢失。 我正在使用以下代码进行上传:

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

扭曲的图片是: enter image description here

1 个答案:

答案 0 :(得分:1)

我使用Apache Commons进行上传,这是我的上传代码,每次都能完美运行......

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

如果您继续看到问题再次发生,我会在您在服务器上获得的文件上使用MD5,并将该值重新发送到响应中,并将其与您发送的文件的本地MD5进行比较。如果它们不一样,你就会知道出了什么问题。