1

I want to upload multiple image at once. so I found 'MultipartEntityBuilder' but It is not working well.

It's my source...

public void executeMultipartPost() throws Exception {
    try {

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(Charset.forName("UTF-8"));
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byteArray = byteArrayOutputStream.toByteArray();


        builder.addTextBody("file1", byteArray.toString());
        builder.addTextBody("file2", byteArray2.toString());

        // send
        InputStream inputStream = null;
        HttpClient httpClient = AndroidHttpClient.newInstance("Android");
        HttpPost httpPost = new HttpPost(UPLOAD_URL);
        httpPost.setEntity(builder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();

        // response
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        inputStream.close();

        // result
        String result = stringBuilder.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

When Debugging, 'httpPost.setEntity(builder.build())' this line is error.

and there is no 'Caused by~' ,but Process: NoSuchFiledError in logcat...

but I think I made image to bitmap then send it to FTP. what is wrong..? Thanks.

Adrian
  • 301
  • 4
  • 15

2 Answers2

1

your code could get rid off the deprecated code of MultipartEntityand use MultipartEntityBuilder. However the specific problem related here is that the core Android libraries conflict with the newly added ones. Also now there are maven repositories available. You could try the following code into the below file:

build.grade (Module:app)
compile('org.apache.httpcomponents:httpmime:4.3.6') {
    exclude module: 'httpclient'
}

compile 'org.apache.httpcomponents:httpclient-android:4.3.5'

Getting NoSuchFieldError INSTANCE org/apache/http/message/BasicHeaderValueParser

Community
  • 1
  • 1
Charuක
  • 12,953
  • 5
  • 50
  • 88
1

public static UploadResult upload(final Bitmap bitmap, final Context context) {

    StringBuilder builder = new StringBuilder();
    UploadResult result = null;
    try {
        URL uri = new URL(context.getString(R.string.base_url) + context.getString(R.string.api_upload));
        HttpURLConnection con = (HttpURLConnection) uri.openConnection();
        con.setConnectTimeout(20000);
        con.setReadTimeout(20000);
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setDoInput(true);

        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("connection", "keep-alive");
        String BOUNDARY = UUID.randomUUID().toString();
        String LINE_END = "\r\n";
        String PREFIX = "--";
        con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);

        OutputStream os = con.getOutputStream();

        String sb = PREFIX +
                BOUNDARY +
                LINE_END +
                "Content-Disposition: form-data; name=\"file\"; filename=\"tmp.png\"" + LINE_END +
                "Content-Type: application/octet-stream; charset=UTF-8" + LINE_END +
                LINE_END;

        os.write(sb.getBytes());
        os.write(Util.Bitmap2Byte(bitmap));

        os.write(LINE_END.getBytes());
        byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
        os.write(end_data);

        os.flush();
        os.close();
        int code = con.getResponseCode();
        System.out.println("code:" + code);
        BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));

        if (code == 200) {
            String ch;
            while (null != (ch = br.readLine())) {
                builder.append(ch);
            }
        }
        con.disconnect();

        String response = builder.toString();
        if (!response.isEmpty()) {
            result = JSON.parseObject(response, UploadResult.class);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}
  • it is the http response, you can change it to String, if response is json or xml, the UploadResult is response entity – named me yi Jul 26 '16 at 01:43
  • JSON is fastjson, you can also change it to gson – named me yi Jul 26 '16 at 01:44
  • got it. Thanks! I will also try!! Thank you! :) – Adrian Jul 26 '16 at 01:46
  • hm... me yi! Can I ask one more thing?? I want to upload multiple!! but this code is only one bitmap. but I want send more than 10 bitmap at once.... T_T – Adrian Jul 26 '16 at 01:48
  • Do I just put more 'os.write(Util.Bitmap2Byte(bitmap));' ?? – Adrian Jul 26 '16 at 01:48
  • if you have more bitmap, you need to circulation String sb = PREFIX + BOUNDARY + LINE_END + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp.png\"" + LINE_END + "Content-Type: application/octet-stream; charset=UTF-8" + LINE_END + LINE_END; os.write(sb.getBytes()); os.write(Util.Bitmap2Byte(bitmap)); os.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes(); os.write(end_data); – named me yi Jul 26 '16 at 01:51
  • if you have more file – named me yi Jul 26 '16 at 03:59
  • That is greate idea! Thanks! loop is start from String sb to os.write(end_data)? and Does it means os.write many times? then one connection?? When I tired, getresponsecode is tooo long time.. as one by one. Can I ask you the reason?? I guess one connection multi sending is more quick than one connection sending one by one. but It is not... – Adrian Jul 27 '16 at 04:20
  • this is only one connection – named me yi Jul 27 '16 at 06:00
  • exactly. so Nice idea. but when I call outputstream.write() manytimes (when I use loop for multiple) it makes error. so I guess... is there max_size of outputstream..?? I'm thinking really thanks to your reply..!! – Adrian Jul 27 '16 at 06:03
  • if HttpURLConnection is not disconnect, this is only one connection, if you want to send more, you only need to loop String sb to os.write(end_data); – named me yi Jul 27 '16 at 06:03
  • oh, may be, the may be have the max_size, may be 64k or more – named me yi Jul 27 '16 at 06:06
  • ah...!!!! so when I try call many times...(sometimes I need more 10 loop), Is it necessary to face error!? – Adrian Jul 27 '16 at 06:08
  • you should change the filename, one bitmap one filename – named me yi Jul 27 '16 at 06:13
  • yep! I always change filename in loop. and error stream is... 500 - ���� ���� ���. – Adrian Jul 27 '16 at 06:20
  • getting from server is broken the String... I don't know ... frankly First error is runtime-error " – Adrian Jul 27 '16 at 06:21
  • 500 - ���� ���� ���. – Adrian Jul 27 '16 at 06:31
  • 0 0;color:#000000;} #header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;background-color:#555555;}#content{margin:0 0 0 2%;position:relative;}.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}-->

    500 - ���� ���� ���.

    ã�� �ִ� ���ҽ��� ����� �־� ǥ���� �� ���ϴ�.

    – Adrian Jul 27 '16 at 06:31
  • these 2 log is whole message getting from error stream. – Adrian Jul 27 '16 at 06:31
  • this string is broken, i see is ���� ���� ��� – named me yi Jul 27 '16 at 06:37
  • Omg... damn!! I got it... may be, may be(as u said. lol) outputstream has a max_size. so I changed like this :: ByteArrayInputStream bs =null; int bytesRead, bytesAvailable, bufferSize;byte[] temp =bitmapToByteArray(bitmap.get(i)); bs = new ByteArrayInputStream(temp);bytesAvailable = bs.available(); int maxBufferSize = 1 * 1024 * 1024; bufferSize = Math.min(bytesAvailable, maxBufferSize); os.write(temp, 0, bufferSize); :: It is uploaded completely...!!! – Adrian Jul 27 '16 at 06:55
  • hm... not 100%.... I try other page.... It is still error..... but I don't know what is common and different...!!!! T_T – Adrian Jul 27 '16 at 07:07