0

I'm trying to upload an image file and an audio file from Android to the Php server at the same time, this is the upload method on Android part:

public String postFile(File image,File audio) throws Exception {

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(uploadUrl);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();        
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    FileBody fbImage = new FileBody(image);
    FileBody fbAudio = new FileBody(audio);

    builder.addPart("image", fbImage);  
    builder.addPart("audio", fbAudio);
    final HttpEntity yourEntity = builder.build();

    class ProgressiveEntity implements HttpEntity {
        @Override
        public void consumeContent() throws IOException {
            yourEntity.consumeContent();                
        }
        @Override
        public InputStream getContent() throws IOException,
                IllegalStateException {
            return yourEntity.getContent();
        }
        @Override
        public Header getContentEncoding() {             
            return yourEntity.getContentEncoding();
        }
        @Override
        public long getContentLength() {
            return yourEntity.getContentLength();
        }
        @Override
        public Header getContentType() {
            return yourEntity.getContentType();
        }
        @Override
        public boolean isChunked() {             
            return yourEntity.isChunked();
        }
        @Override
        public boolean isRepeatable() {
            return yourEntity.isRepeatable();
        }
        @Override
        public boolean isStreaming() {             
            return yourEntity.isStreaming();
        } // CONSIDER put a _real_ delegator into here!

        @Override
        public void writeTo(OutputStream outstream) throws IOException {

            class ProxyOutputStream extends FilterOutputStream {

                public ProxyOutputStream(OutputStream proxy) {
                    super(proxy);    
                }
                public void write(int idx) throws IOException {
                    out.write(idx);
                }
                public void write(byte[] bts) throws IOException {
                    out.write(bts);
                }
                public void write(byte[] bts, int st, int end) throws IOException {
                    out.write(bts, st, end);
                }
                public void flush() throws IOException {
                    out.flush();
                }
                public void close() throws IOException {
                    out.close();
                }
            } // CONSIDER import this class (and risk more Jar File Hell)

            class ProgressiveOutputStream extends ProxyOutputStream {
                public ProgressiveOutputStream(OutputStream proxy) {
                    super(proxy);
                }
                public void write(byte[] bts, int st, int end) throws IOException {

                    // FIXME  Put your progress bar stuff here!

                    out.write(bts, st, end);

                    if(end==bts.length-1){
                        dialog.dismiss();
                        Toast.makeText(TakePhotoActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            yourEntity.writeTo(new ProgressiveOutputStream(outstream));
        }

    };
    ProgressiveEntity myEntity = new ProgressiveEntity();

    post.setEntity(myEntity);
    HttpResponse response = client.execute(post); 

    System.out.println("UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU "+getContent(response));

    return getContent(response);

} 

public static String getContent(HttpResponse response) throws IOException {
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String body = "";
    String content = "";

    while ((body = rd.readLine()) != null) 
    {
        content += body + "\n";
    }
    return content.trim();
}

And this is the Php part:

<?php

$file_path = "uploads/";

$file_path = $file_path . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
    echo "image success";
} else{
    echo "image fail";
}

$file_path = $file_path . basename( $_FILES['audio']['name']);
if(move_uploaded_file($_FILES['audio']['tmp_name'], $file_path)) {
    echo "audio success";
} else{
    echo "audio fail";
}
?>

But on the server I can only see the audio file, the image file failed uploading, I also tried to upload two image files, it worked, but when one audio file and one image file, the image file usually failed, any suggestions about this? Thank you in advance.

betteroutthanin
  • 7,148
  • 8
  • 29
  • 48
  • You can consume Content only at once from an Entity. But you have `yourEntity.consumeContent();` and this `return yourEntity.getContent();` and more. So i guess that is why the excpetion – Raghunandan Jan 12 '14 at 15:09
  • @Raghunandan, it worked when uploading only one file, but when I tried to upload two at the same time, only one file was uploaded, BTW, the code was from [here](http://stackoverflow.com/questions/18964288/upload-a-file-through-an-http-form-via-multipartentitybuilder-with-a-progress/19188010#19188010) – betteroutthanin Jan 12 '14 at 15:16
  • i you want parallel upload why don't you use a executor? – Raghunandan Jan 12 '14 at 15:20
  • @Raghunandan, I'm new to android, can you be a little more detailed about executor? Thank you very much – betteroutthanin Jan 12 '14 at 15:35
  • BTW, I wrote the original of some of that. I called that stuff "Java-Heresy" specifically because real code must clean it up. And everyone copy the top part of my post at http://stackoverflow.com/questions/18964288/upload-a-file-through-an-http-form-via-multipartentitybuilder-with-a-progress into here unless you actually NEED a progress bar! . See also http://stackoverflow.com/questions/22101515/how-to-send-multiple-images-from-android-to-a-wcf-rest-service-as-a-stream-to-wr – Phlip Mar 13 '14 at 14:36
  • @Phlip I used App Engine instead of PHP for the app, but thank you anyway. – betteroutthanin Mar 13 '14 at 15:40
  • 1
    i mean take out the copy-pasta code! it makes your problem easier to solve – Phlip Mar 13 '14 at 15:43

1 Answers1

0

I would suggest you follow up with this . as your MultipartEntity is different and this one works.I've tried it. Happy Coding!

    try
    {
        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(URL);

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        entityBuilder.addTextBody(USER_ID, userId);
        entityBuilder.addTextBody(NAME, name);
        entityBuilder.addTextBody(TYPE, type);
        entityBuilder.addTextBody(COMMENT, comment);
        entityBuilder.addTextBody(LATITUDE, String.valueOf(User.Latitude));
        entityBuilder.addTextBody(LONGITUDE, String.valueOf(User.Longitude));

        if(file != null)
        {
            entityBuilder.addBinaryBody(IMAGE, file);
        }

        HttpEntity entity = entityBuilder.build();

        post.setEntity(entity);

        HttpResponse response = client.execute(post);

        HttpEntity httpEntity = response.getEntity();

        result = EntityUtils.toString(httpEntity);

        Log.v("result", result);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
Community
  • 1
  • 1