我在android中实现以下功能时被卡住了,其实我在android新API(API 29)方面没有太多工作经验。
1- 从图库中挑选视频,它给了我URI,我按照这个创建了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步: 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-将安卓文件从图库存储到缓存,然后尝试上传,但同样的问题。现在对我来说有点溢出
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)
}
鼎力相助
嗨,经过长时间的挖掘,我找到了解决方案,现在它的工作。