RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 952296
Accepted
Alex
Alex
Asked:2020-03-04 23:15:41 +0000 UTC2020-03-04 23:15:41 +0000 UTC 2020-03-04 23:15:41 +0000 UTC

通过网络传输android文件

  • 772

大家好。我没有使用android的经验,所以我遇到了这个问题,我无法以任何方式解决。

问题是无法从 android 发送 115MB 的视频文件。

它是如何表达的:

更准确地说,在 115Mb 中,有 52Mb 进入服务器,传输停止在那里。服务器返回 code = 200 并写入它已收到一个 52MB 的文件。虽然从应用程序发送了一个 60MB 的文件 - 没问题!

下面是使用的代码示例。

    private class UploadImageTask extends AsyncTask<String, Void, List<File>> {
    protected List<File> doInBackground(String... args) {
        runOnUiThread(new Runnable() {
            public void run() {
                resultTextView.append("\nuploading started.....");
            }
        });

        for (File file : fileList){
            uploadFile(file);
        }

        return null; //loadImageFromNetwork(urls[0]);
    }

    protected void onPostExecute(List<File> list) {
        resultTextView.append("\nUPLOAD -> STATE: " + MultipartUtility.status);
        resultTextView.append("\nUPLOAD -> END");
        Toast.makeText(getApplicationContext(), "UPLOAD: -> END", Toast.LENGTH_LONG).show();
    }
}




public int uploadFile(File sourceFile) {


    final String fileName = sourceFile.getName();

    HttpsURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable;//, bufferSize;
    byte[] buffer;
    int maxBufferSize = 4 * 1024 * 1024;
    long fileSize = sourceFile.length();

    if (!sourceFile.isFile()) {

        Log.e("uploadFile", "Source File not exist :"
                //+ uploadFilePath + "" + uploadFileName);
                + sourceFile.getName()
        );

        runOnUiThread(new Runnable() {
            public void run() {
                resultTextView.append("Source File not exist :"
                        //+uploadFilePath + "" + uploadFileName);
                        + fileName
                );
            }
        });

        return 0;

    }
    else
    {
        try {

            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);

            // Open a HTTP  connection to  the URL
            conn = (HttpsURLConnection) url.openConnection();
            conn.setConnectTimeout(360000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "bearer " + token.getAccess());
            conn.setRequestProperty("Connection", "Keep-Alive" );
            conn.setRequestProperty("ENCTYPE", "multipart/form-data" );
            conn.setRequestProperty("Transfer-Encoding","chunked" );
            conn.setChunkedStreamingMode(1024);
            //conn.setRequestProperty("file", sourceFile.getPath());
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("file", fileName);

            dos = new DataOutputStream(conn.getOutputStream());

            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\""
                            + fileName + "\"" + lineEnd
            );

                    dos.writeBytes(lineEnd);

            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);

                sendBytes = sendBytes + bytesRead;

                runOnUiThread(new Runnable() {
                    public void run() {
                        sizeTextView.setText("BUFFER-SIZE: " + bufferSize + "\nNAME: " + fileName + "\nSIZE: " + sendBytes);
                    }
                });
            }


            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            serverResponseCode = conn.getResponseCode();
            String serverResponseMessage = conn.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);

            if(serverResponseCode == 200){

                runOnUiThread(new Runnable() {
                    public void run() {

                        resultTextView.append("\nUPLOAD-CODE: " + serverResponseCode);
                        String msg = "\nFile Upload Completed.\n\n See uploaded file here : \n\n"
                                + fileName;

                        resultTextView.append(msg);
                        Toast.makeText(UploadActivity.this, "File Upload Complete.",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            ex.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    resultTextView.append("MalformedURLException Exception : check script url.");
                    Toast.makeText(UploadActivity.this, "MalformedURLException",
                            Toast.LENGTH_SHORT).show();
                }
            });

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {

            e.printStackTrace();

            runOnUiThread(new Runnable() {
                public void run() {
                    resultTextView.append("Got Exception : see logcat ");
                    Toast.makeText(UploadActivity.this, "Got Exception : see logcat ",
                            Toast.LENGTH_SHORT).show();
                }
            });
            Log.e("Upload-Exception", "Exception : "
                    + e.getMessage(), e);
        }
        return serverResponseCode;

    } // End else block
}

AndroidManifest

        android:allowBackup="true"
    android:hardwareAccelerated="false"
    android:largeHeap="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

测试服务器时,没有发现任何问题!相同的文件传输方法在带有 -Xmx10M 的普通控制台模式(机器人)下效果很好;

服务器:

@PostMapping("/{id}/file")
public void uploadFile(@PathVariable("id") Request request, @RequestParam("file") MultipartFile[] files){
    log.info("==========================================");
    log.info("===uploadFile2:start:" + request.getId());

    if (files.length<1) {
        throw new StorageException("No Files");
    }

    try {

        FileUpload.saveUploadedFiles(Arrays.asList(files), "/request/1266123/");

    } catch (IOException e) {
        throw new StorageException("File upload error", e);
    }

    log.info("Successfully uploaded - " + files.length);

}

提前感谢您的回复。

PS / 感觉好像只从原始流中读取了52MB,然后发送。

java
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Alex
    2020-03-05T02:04:11Z2020-03-05T02:04:11Z

    此代码完全有效。问题出在文件本身,事实证明,文件已损坏,重达 52MB

    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5