Android: Sending an image through POST

2019-02-19 22:47发布

I've been searching around for the solution, and have come across the multipart and different setups, but I can't seem to get it working correctly.

Here's what I have so far.

Edit: The server side error I'm getting is a 500. I assume that's because the data I'm sending is either too big for one request or is in an incorrect format.

                    ByteArrayOutputStream bao = new ByteArrayOutputStream();

                    bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);

                    byte [] ba = bao.toByteArray();

                    String ba1=Base64.encodeToString(ba,Base64.URL_SAFE);

                    mParams.add(new BasicNameValuePair("story[image]",ba1));

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(mPath);
    // Add your data
    try
    {
        httppost.setHeader("Authorization", Base64.encodeToString(new StringBuilder(sssss).append(":").append(ssssss).toString().getBytes("UTF-8"), Base64.URL_SAFE|Base64.NO_WRAP));
        httppost.setEntity(new UrlEncodedFormEntity(mParams));
        HttpResponse rH = httpclient.execute(httppost);
        Log.v(TAG, "response: " + rH.toString());
        int f = 0;
    }
    catch(HttpResponseException e)
    {
        Log.e(TAG, e.getLocalizedMessage());
        Log.e(TAG, e.getMessage());
        e.printStackTrace();
    }

1条回答
放我归山
2楼-- · 2019-02-19 23:18

This is what I did yesterday, maybe it will help

        Bitmap bitmapOrg = images.get(0);

        ByteArrayOutputStream bao = new ByteArrayOutputStream();

        String upload_url = prepare_upload_url();
        bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);

        byte[] data = bao.toByteArray();

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(upload_url);
        MultipartEntity entity = new MultipartEntity(
                HttpMultipartMode.BROWSER_COMPATIBLE);

        //Set Data and Content-type header for the image
        entity.addPart("file",
                new ByteArrayBody(data, "image/jpeg", "file"));
        postRequest.setEntity(entity);
        try {

            HttpResponse response = httpClient.execute(postRequest);
        //Read the response
            String jsonString = EntityUtils.toString(response.getEntity());
            Log.v(ProgramConstants.TAG, "after uploading file "
                    + jsonString);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
查看更多
登录 后发表回答