Android Uploading large files

做~自己de王妃 提交于 2019-12-05 17:32:55

This may be helpful.

private void uploadFile(File file) throws IOException {
    Log.i(TAG, "Uploading " + file);
    String videoName = file.getParentFile().getName();

    AndroidHttpClient httpclient = AndroidHttpClient.newInstance(GoProLive.TAG);
    try {
        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), ConnectTimeout);
        HttpConnectionParams.setSoTimeout(httpclient.getParams(), DataTimeout);
        HttpPost post = new HttpPost(
                String.format("http://" + ServerName + "/upload/%s/%s", user.getUsername(), file.getName()));
        post.setEntity(new FileEntity(file, "application/octet-stream"));

        SimpleDateFormat df = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT, Locale.US);
        df.applyPattern("EEE, dd MMM yyyy HH:mm:ss z");
        post.setHeader("Last-Modified", df.format(new Date(file.lastModified())));
        HttpResponse httpResponse = executePost(httpclient, post);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            file.delete();
        } else {
            throw new HttpException("Failed to upload file " + file.getAbsolutePath(), statusCode);
        }
    } finally {
        httpclient.close();
    }
}

You can't load the entire file into memory -- on many devices, you're limited to 16MB or 32MB of heap. You should stream the file to the server in small chunks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!