更好的方法来上传/多个文件下载到服务器 [英] better method to upload/download multiple files to the server

查看:85
本文介绍了更好的方法来上传/多个文件下载到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用

@Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub
        String path = "http://192.168.1.112/johnson/learn/android/uploads/";
        String sUrl1 = "productSock";
        String sUrl2 = "productHistory";
        downloadFile(path, sUrl2);
        downloadFile(path, sUrl1);
        return null;
    }

    private boolean downloadFile(String path, String sUrl) {
        // TODO Auto-generated method stub
        try {
            String toUrl = path + sUrl;
            URL url = new URL(toUrl);
            URLConnection connection = url.openConnection();
            connection.connect();
            // this will be useful so that you can show a typical 0-100%
            // progress bar
            int fileLength = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(Environment
                    .getExternalStorageDirectory().getAbsolutePath()
                    + "/Android/data/com.android.avs.amp.inventory/files/"
                    + sUrl);

            byte data[] = new byte[1024];
            long total = 0;
            int count = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress((int) (total * 100 / fileLength));
                output.write(data);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
        }
        return true;
    }

上传第二个文件

当它停留在31%
有时还停留在一号文件0%

when upload the second file it stuck at 31% sometimes also stuck at the 1st file on 0%

如何改变code?
或任何其他的方法呢?

how to change the code? or any other methods?

和我的上传

@Override
    protected Boolean doInBackground(Void... params) {
        // TODO Auto-generated method stub
        uploadFile("productStock");
        uploadFile("productHistory");
        return false;
    }

    private void uploadFile(String path) {
        // TODO Auto-generated method stub
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/Android/data/com.android.avs.amp.inventory/files/"+path;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String responseFromServer = "";
        String urlString = "http://192.168.1.112/johnson/learn/android/";
        try {
            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }
            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            fileInputStream.close();
            dos.flush();
            dos.close();
        } catch (MalformedURLException ex) {
            // Log.e("Debug", "error: " + ex.getMessage(), ex);
            mErrorMsg = "error: " + ex.getMessage();
        } catch (IOException ioe) {
            // Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            mErrorMsg = "error: " + ioe.getMessage();
        } 
        // ------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {
                // Log.e("Debug", "Server Response " + str);
                mErrorMsg = "Upload Successful";
            }
            inStream.close();

        } catch (IOException ioex) {
            // Log.e("Debug", "error: " + ioex.getMessage(), ioex);
            mErrorMsg = "error: " + ioex.getMessage();
        }
    }

当上传的文件是不存在的,它会停留在进度对话框
或者有没有更好的方法来上传多个文件?

When the file to upload is not exist, it will stuck at progress dialog or is there any better method to upload multiple files?

在此先感谢

推荐答案

我不知道是什么原因导致你的code在一定的百分比挂,但我可以告诉你为什么它会产生损坏的数据。

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.

在上传/下载code你用这个方法来写你读取的字节:

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

stream.write(buffer, 0, bufferSize);

现在,这个问题是,你给的<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/io/OutputStream.html#write%28byte%5B%5D,%20int,%20int%29\"相对=nofollow> 写(字节[],INT,INT) -method 的长度错误的参数。

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

从流读取时,<一个href=\"http://docs.oracle.com/javase/6/docs/api/java/io/InputStream.html#read%28byte%5B%5D,%20int,%20int%29\"相对=nofollow> 阅读() -method回报的:

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

返回:字节读入缓冲区总数或-1,如果
  没有更多的数据,因为该流的末尾已到达

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.

这意味着,甚至认为你的字节[] 阵列 BUFFER_SIZE 字节长(例如1024),这并不意味着1024个字节,其中阅读(它可能是更小,例如在缓冲可能不充分)。字节的实际金额读取返回的阅读() -method。

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.

为此,你给了的write() -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);
}

如果你不上传二进制数据,你通常最好使用已经缓冲的作家的实现(如的的BufferedWriter /的的BufferedReader )。

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

这篇关于更好的方法来上传/多个文件下载到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆