我坚持在android中实现以下功能实际上我在android新api(api29)方面没有太多的工作经验
1-从gallery中挑选视频,它给了我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-这是我的改装代码:
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);
}
上面的restapi可以很好地处理postman请求,但是从改型调用来看它不起作用。我想我做错了什么。
我正在努力实现这个功能,因为4-5天,应用多种解决方案,如
1-将android文件从gallery存储到缓存,然后尝试上载,但问题相同。现在对我来说有点过分了
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)
}
任何帮助都是值得赞赏的
1条答案
按热度按时间mrphzbgm1#
嗨,经过长时间的挖掘,我找到了解决方案,现在它正在工作:
spring boot multipartfile始终为空