【问题标题】:Android upload file in chunks to PHPAndroid分块上传文件到PHP
【发布时间】:2014-06-16 14:44:18
【问题描述】:

我们如何将大文件分块上传到 PHP 服务器,以便在连接断开时,可以随时恢复上传。

具体来说,Android 中需要哪些库来执行此操作?

用户正在从互联网连接缓慢/不稳定的国家/地区上传大文件。谢谢

编辑

更多信息,我目前正在使用 HTTP POST 一次上传整个文件。如下代码所示:

private int uploadFiles(File file) {
        String zipName = file.getAbsolutePath() + ".zip";
        if(!zipFiles(file.listFiles(), zipName)){
            //return -1;
            publishResults(-1);
        }
        //publishProgress(-1, 100);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String serverUrl = prefs.getString("serverUrl", "ServerGoesHere"); // todo ensure that a valid string is always stored
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        int responseCode = -1;
        try {
            //notif title, undeterministic
            pNotif.setContentText("Zipping complete. Now Uploading...")
                  .setProgress(0, 0, true);
            mNotifyManager.notify(NOTIFICATION_ID, pNotif.build()); // make undeterministic

            //update progress bar to indeterminate
            sendUpdate(0, 0, "Uploading file."); // sendupdate using intent extras

            File uploadFile = new File(zipName);
            long totalBytes = uploadFile.length();
            FileInputStream fileInputStream = new FileInputStream(uploadFile);

            URL url = new URL(serverUrl);
            connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");

            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream
            .writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + zipName + "\"" + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            long bytesUploaded = 0;
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {
                bytesUploaded += bytesRead;
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                //int percentCompleted = (int) ((100 * bytesUploaded) / totalBytes);
                //publishProgress((int)bytesUploaded/1024, (int)totalBytes/1024);

                System.out.println("bytesRead> " + bytesRead);
            }

            //publishProgress(-2, 1); // switch to clean up
            outputStream.writeBytes(lineEnd);
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);
            try {
                responseCode = connection.getResponseCode();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            fileInputStream.close();
            outputStream.flush();
            outputStream.close();
            // Delete the zip file
            new File(zipName).delete();
        } catch (Exception ex) {
            new File(zipName).delete();
            responseCode = -1;
            ex.printStackTrace();
        } 
        return responseCode;
    }

有没有办法修改它以分块发送?我做的大部分研究都不是很清楚,对不起

【问题讨论】:

  • 你不能向服务器发送另一个请求,告诉它上传完成了吗?或者准备文件:temp_file 到几个文件中,foreach 文件调用网络服务器(一个历史函数)并标记部分上传,你会知道 10 个文件中有 5 个文件被成功插入
  • 传输控制协议 (TCP) 旨在确保每个数据包以正确的顺序到达并且不会丢失。您可以只使用 HTTP PUT 或 POST 方法进行上传,因为 HTTP 使用 TCP。
  • 我正在使用 HTTP POST 发送整个文件 @TmKVU。
  • @KA_lin 所以我需要为每个块打开一个连接?
  • @apSTRK 如果您想分块上传,HTTP 不是要使用的协议。 HTTP 是无状态的,您确实需要为每个块打开一个连接。我会使用套接字编程并在您的应用程序和服务器之间保持 TCP 连接,直到上传完成。

标签: php android upload chunked


【解决方案1】:

通过 HTTP 以块的形式上传文件不是一个好主意,因为它是一种无状态协议,您需要为要发送到服务器的每个块建立一个新连接。此外,您必须手动维护此传输之间的状态,并且无法保证文件将按照发送的顺序到达。

您应该使用带有 TCP 套接字的套接字编程,该套接字在整个文件发送之前保持连接。然后,您可以将块推入套接字,它们将无损地到达,并且按照它们被送入套接字的顺序。

【讨论】:

    【解决方案2】:

    我最终使用 SFTP 库实现了可恢复上传。 JSchhttp://www.jcraft.com/jsch/ 我使用 SFTP 上传,库处理可恢复模式。示例代码:

    JSch jsch = new JSch();
    session = jsch.getSession(FTPS_USER,FTPS_HOST,FTPS_PORT);
    session.setPassword(FTPS_PASS);
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    channel = session.openChannel("sftp");
    channel.connect();
    channelSftp = (ChannelSftp)channel;
    channelSftp.cd(FTPS_PATH);
    
    File uploadFile = new File(zipName); // File to upload
    totalSize = uploadFile.length(); // size of file
    
    // If part of the file has been uploaded, it saves the number of bytes. Else 0
    try {
        totalTransfer = channelSftp.lstat(uploadFile.getName()).getSize();
    } catch (Exception e) {
        totalTransfer = 0;
    }
    
    // Upload File with the resumable attribute
    channelSftp.put(new FileInputStream(uploadFile), uploadFile.getName(), new SystemOutProgressMonitor(), ChannelSftp.RESUME);
    
    channelSftp.exit();
    session.disconnect();
    

    有了这个库,我满足了所有要求:可恢复上传和上传进度。

    【讨论】:

    • 我认为您可以在发送文件时使用 socket.io 来维护您的连接,一旦完成,您可以发送一个事件来表示它已完成!我用 Node JS 在 web 上做了它,我不使用 PHP 来做它。所以我想在android中做同样的事情我使用了这个链接code.tutsplus.com/tutorials/…
    猜你喜欢
    • 2017-01-08
    • 2021-08-30
    • 1970-01-01
    • 2016-09-26
    • 2016-03-19
    • 2017-12-24
    • 2011-01-27
    • 1970-01-01
    • 2013-11-13
    相关资源
    最近更新 更多