Android - 如何使用 OkHTTP 分块上传视频? [英] Android - how to upload video in chunks using OkHTTP?
问题描述
请参阅我用于将视频上传到服务器的以下代码.但是,对于足够大的视频,我收到 OutOfMemory 异常.
please see my below code which I use to upload a video to a server. However, for large enough videos, I'm getting an OutOfMemory exception.
InputStream stream = getContentResolver().openInputStream(videoUri);
byte[] byteArray = IOUtils.toByteArray(stream);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "fname",
RequestBody.create(MediaType.parse("video/mp4"), byteArray))
.build();
Request request = new Request.Builder()
.url(uploadURL)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient.Builder().build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
有人能指出我如何避免 OutOfMemory 异常的正确方向吗?有没有办法可以从 InputStream 转到 requestBody?
Can someone point me in the right direction on how to avoid OutOfMemory exception? Is there a way I can go from the InputStream to the requestBody?
推荐答案
您可以创建一个自定义的 RequestBody
来传输数据.您必须小心:它可能会被多次重用,因为 OkHttp 可能决定重试请求.确保每次都可以从头开始重新打开 InputStream
.
You can create a custom RequestBody
which streams the data. You will have to take some care: it may be reused multiple times because OkHttp may decide to retry the request. Make sure you can re-open the InputStream
from the start each time.
ContentResolver contentResolver = context.getContentResolver();
final String contentType = contentResolver.getType(videoUri);
final AssetFileDescriptor fd = contentResolver.openAssetFileDescriptor(videoUri, "r");
if (fd == null) {
throw new FileNotFoundException("could not open file descriptor");
}
RequestBody videoFile = new RequestBody() {
@Override public long contentLength() { return fd.getDeclaredLength(); }
@Override public MediaType contentType() { return MediaType.parse(contentType); }
@Override public void writeTo(BufferedSink sink) throws IOException {
try (InputStream is = fd.createInputStream()) {
sink.writeAll(Okio.buffer(Okio.source(is)));
}
}
};
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", "fname", videoFile)
.build();
Request request = new Request.Builder()
.url(uploadURL)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
try {
fd.close();
} catch (IOException ex) {
e.addSuppressed(ex);
}
Log.e(TAG, "failed", e);
}
@Override public void onResponse(Call call, Response response) throws IOException {
fd.close();
}
});
这篇关于Android - 如何使用 OkHTTP 分块上传视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!