问题
I am stuck to achieve below functionality in android actually I dont have much working experience in android new APIs (API 29)
1- Picked video from gallery, it gave me URI and I created IputeStreamRequestBody as per this thread
Here is my code for that:
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);
}
}
}
Step: 3- Here is my retrofit code:
public interface PlatformGroupPostService {
@Multipart
@POST("brainy/api/v0/post")
Observable<NewGroupAPIResponse> createPost(@Part("postData") RequestBody postData,
@Part MultipartBody.Part attachments);
}
Request hit the server with null instance of file here is my Rest call:
//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);
}
above rest API is working fine with PostMan request but from Retrofit call its not working. I think I am doing something wrong.
I am struggling to achieve this feature since 4-5 days, applies multiple solution, Like
1- store android file from gallery to cache and then tries to upload it, but same issue. Now kind of overflow for me
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)
}
any help would be really appreciable
回答1:
Hi after long digging I found solution and its working now:
Spring Boot multipartfile always null
来源:https://stackoverflow.com/questions/62275348/issue-to-upload-video-file-from-android-device-to-springboot-rest-api