Skip to content Skip to sidebar Skip to footer

Better Method To Upload/download Multiple Files To The Server

I tried to use : @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub String path = 'http://192.168.1.112/johnson/lea

Solution 1:

I'm not sure what causes your code to hang at a certain percentage, but I can tell you why it will produce corrupted data.

In the Upload/Download code you use this method to write your read bytes:

stream.write(buffer, 0, bufferSize);

Now, the problem with this is, that you're giving the write(byte[], int, int)-method the wrong parameter for the length.

When reading from a stream, the read()-method returns:

Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

That means, even thought your byte[] array is buffer_size bytes long (for example 1024), this does not mean that 1024 bytes where read (it might be less, e.g. the buffer might not be full). The actual amount of bytes read is returned by the read()-method.

Therefor, you're giving the write()-method the wrong amount of bytes to write, which causes it to write null-bytes that corrupt your file.

The correct implementation looks like this:

byte data[] = new byte[1024];
int read_count = 0;
while ((read_count = input.read(data, 0, data.length)) != -1) {
    output.write(data, 0, read_count);
}

If you're not uploading binary data, you're normally better off using an already buffered writer-implementation (like BufferedWriter / BufferedReader).


I covered this topic in a little more detail in this Blogpost: Working unbuffered streams

Post a Comment for "Better Method To Upload/download Multiple Files To The Server"