如何在android中快速上传大视频文件到服务器

Kri*_*ish 2 android

嗨,我正在使用 Volley Multi-part Api 将大型视频文件上传到服务器,但上传到服务器需要很多时间

拆分我的视频文件并发送到服务器是否更好?如果更好,请向我提供代码我该怎么做,如果不是,将大视频文件快速上传到服务器的最佳方法是什么?

Vla*_*nko 5

将文件拆分为多个部分(块):

public static List<File> splitFile(File f) throws IOException {
    int partCounter = 1;
    List<File> result = new ArrayList<>();
    int sizeOfFiles = 1024 * 1024;// 1MB
    byte[] buffer = new byte[sizeOfFiles]; // create a buffer of bytes sized as the one chunk size

    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
    String name = f.getName();

    int tmp = 0;
    while ((tmp = bis.read(buffer)) > 0) {
        File newFile = new File(f.getParent(), name + "." + String.format("%03d", partCounter++)); // naming files as <inputFileName>.001, <inputFileName>.002, ...
        FileOutputStream out = new FileOutputStream(newFile);
        out.write(buffer, 0, tmp);//tmp is chunk size. Need it for the last chunk, which could be less then 1 mb.
        result.add(newFile);
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

此方法会将您的文件拆分为 1MB 大小的块(不包括最后一个块)。之后,您也可以将所有这些块发送到服务器。

此外,如果您需要合并这些文件:

public static void mergeFiles(List<File> files, File into)
        throws IOException {
   BufferedOutputStream mergingStream = new BufferedOutputStream(new FileOutputStream(into))
    for (File f : files) {
        InputStream is = new FileInputStream(f);
        Files.copy(is, mergingStream);
        is.close();
    }
    mergingStream.close();
}
Run Code Online (Sandbox Code Playgroud)

以防万一您的服务器也使用 Java