【发布时间】:2020-06-09 05:01:29
【问题描述】:
我坚持在 android 中实现以下功能实际上我在 android 新 API (API 29) 方面没有太多工作经验
1- 从图库中挑选视频,它给了我 URI,我根据 thread 创建了 IputeStreamRequestBody
这是我的代码:
public class InputStreamRequestBody extends RequestBody {
private final MediaType contentType;
private final ContentResolver contentResolver;
private final Uri uri;
public InputStreamRequestBody(MediaType contentType, ContentResolver contentResolver, Uri uri) {
if (uri == null) throw new NullPointerException("uri == null");
this.contentType = contentType;
this.contentResolver = contentResolver;
this.uri = uri;
}
@Nullable
@Override
public MediaType contentType() {
return contentType;
}
@Override
public long contentLength() {
return -1;
}
@Override
public void writeTo(@NonNull BufferedSink sink) throws IOException {
try (Source source = Okio.source(contentResolver.openInputStream(uri))) {
sink.writeAll(source);
}
}
}
步骤:3- 这是我的改造代码:
public interface PlatformGroupPostService {
@Multipart
@POST("brainy/api/v0/post")
Observable<NewGroupAPIResponse> createPost(@Part("postData") RequestBody postData,
@Part MultipartBody.Part attachments);
}
请求使用空文件实例访问服务器,这是我的 Rest 调用:
//attachments always coming null
public ResponseEntity<?> createPost(@RequestParam String postData,
@RequestPart(value = "attachments", required = false)
MultipartFile attachments) {
PostEntity postEntity = getPostEntity(postData);
return new ResponseEntity<>(postService.createPost(postEntity, attachments), HttpStatus.CREATED);
}
以上 API 在 PostMan 请求下工作正常,但从 Retrofit 调用它不工作。我觉得我做错了什么。
自 4-5 天以来,我一直在努力实现此功能,应用多种解决方案,喜欢
1- 将 android 文件从画廊存储到缓存,然后尝试上传,但同样的问题。现在对我来说有点溢出了
fun prepareFilePart(partName: String, uri: Uri, context: Context, name: String): MultipartBody.Part {
val inputStream = context.contentResolver.openInputStream(uri)
val file = File(context.cacheDir, name+".mp4")
val fos = FileOutputStream(file)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (inputStream != null) {
FileUtils.copy(inputStream, fos)
}
} else {
}
fos.flush();
fos.getFD().sync();
fos.close();
val requestBody: RequestBody =
RequestBody.create(MediaType.parse(context.contentResolver.getType(uri)), file)
return MultipartBody.Part.createFormData(partName, name, requestBody)
}
任何帮助都会很重要
【问题讨论】:
-
在this OkHttp GitHub issue comment 中尝试第二个
InputStreamRequestBody实现。如果您阅读完整的问题,包括 Jake Wharton 的 cmets,您会明白为什么InputStreamRequestBody需要能够创建InputStream(通过Uri和ContentResolver),而不仅仅是包装一个。 -
@CommonsWare 也没有用,对我来说太复杂了
-
@CommonsWare 你能帮忙吗? stackoverflow.com/questions/62783444/…
-
@SandeepTiwari 你能帮忙吗? stackoverflow.com/questions/62783444/…
标签: android spring-boot retrofit2 multipartform-data