使用 OkHttp 分段上传大文件 [英] Uploading a large file in multipart using OkHttp
本文介绍了使用 OkHttp 分段上传大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 OKhttp 在 Android 中以多部分方式上传单个大文件(更具体地说,到 s3)有哪些选择?
What are my options for uploading a single large file (more specifically, to s3) in multipart in Android using OKhttp?
推荐答案
来自 OkHttp Recipes 页面,这个代码将图像上传到 Imgur:
From the OkHttp Recipes page, this code uploads an image to Imgur:
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addPart(
Headers.of("Content-Disposition", "form-data; name="title""),
RequestBody.create(null, "Square Logo"))
.addPart(
Headers.of("Content-Disposition", "form-data; name="image""),
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
您需要将其调整到 S3,但您需要的类应该相同.
You'll need to adapt this to S3, but the classes you need should be the same.
这篇关于使用 OkHttp 分段上传大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文