gpt4 book ai didi

android - 使用 OkHttp 分段上传大文件

转载 作者:IT老高 更新时间:2023-10-28 22:05:09 28 4
gpt4 key购买 nike

在 Android 中使用 OKhttp 在多部分中上传单个大文件(更具体地说,到 s3)有哪些选择?

最佳答案

获取 OkHttp 2.1,并使用 MultipartBuilder.addFormDataPart() 将文件名作为参数。

       /**
* Upload Image
*
* @param memberId
* @param sourceImageFile
* @return
*/
public static JSONObject uploadImage(String memberId, String sourceImageFile) {

try {
File sourceFile = new File(sourceImageFile);

Log.d(TAG, "File...::::" + sourceFile + " : " + sourceFile.exists());
//Determining the media type
final MediaType MEDIA_TYPE = sourceImageFile.endsWith("png") ?

MediaType.parse("image/png") : MediaType.parse("image/jpeg");


RequestBody requestBody = new MultipartBuilder()
.type(MultipartBuilder.FORM)
.addFormDataPart("member_id", memberId)
.addFormDataPart("file", "profile.png", RequestBody.create(MEDIA_TYPE, sourceFile))
.build();

Request request = new Request.Builder()
.url(URL_UPLOAD_IMAGE)
.post(requestBody)
.build();

OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
return new JSONObject(response.body().string());

} catch (UnknownHostException | UnsupportedEncodingException e) {
Log.e(TAG, "Error: " + e.getLocalizedMessage());
} catch (Exception e) {
Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
}
return null;
}

#Edited for okhttp3:

compile 'com.squareup.okhttp3:okhttp:3.4.1'

RequestBody 替换为:

RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("uploaded_file", filename, RequestBody.create(MEDIA_TYPE_PNG, sourceFile))
.addFormDataPart("result", "my_image")
.build();

#在 GITHUB 上上传演示:##我已经为 Multiple Image Upload 添加了我的答案:)

关于android - 使用 OkHttp 分段上传大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24279563/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com