【问题标题】:Issue to Upload video file from android device to SpringBoot Rest API将视频文件从 android 设备上传到 Spring Boot Rest API 的问题
【发布时间】: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)
}

任何帮助都会很重要

【问题讨论】:

标签: android spring-boot retrofit2 multipartform-data


【解决方案1】:

您好,经过长时间的挖掘,我找到了解决方案并且现在可以使用:

Spring Boot multipartfile always null

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 2018-04-04
    • 2023-03-28
    • 2018-10-08
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    相关资源
    最近更新 更多