Blazor WebAssembly上传视频至api.video失败求助
解决api.video Blazor上传视频报错"Bad Request, the file does not exist in the request"
你的问题出在请求格式不符合api.video上传接口要求:你用JSON格式传递base64编码的文件内容,但api.video的视频上传接口需要的是multipart/form-data格式的文件上传,而非JSON中的bytes字段,所以接口无法识别到文件,返回错误。
修复步骤:
- 移除Base64编码:直接上传原始字节数组,无需转Base64(转码会增加文件体积,降低上传效率)。
- 改用MultipartFormDataContent构造请求体:这是文件上传的标准格式,api.video接口要求通过
file参数接收文件。
修改后的完整代码:
OnSelectFile方法调整:
public async Task OnSelectFile(InputFileChangeEventArgs e) { if (e.File != null) { long maxFileSize = 1024L * 1024L * 1024L * 2L; IBrowserFile videoFile = e.File; // 直接读取字节数组,不转Base64 var buffers = new byte[videoFile.Size]; await videoFile.OpenReadStream(maxFileSize).ReadAsync(buffers); if (await videoClient.UploadVideo(currentVideoObject, buffers, videoFile.ContentType, videoFile.Name)) { toast.ShowToast("Successfully uploaded Video", ToastLevel.Success); } else { toast.ShowToast("Failed to upload video", ToastLevel.Error); } } }
UploadVideo方法重写:
public async Task<bool> UploadVideo(VideoObject video, byte[] fileBytes, string contentType, string fileName) { try { var request = new HttpRequestMessage(HttpMethod.Post, $"https://ws.api.video/videos/{video.Id}/source"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.accesstoken); // 构造multipart/form-data请求体 var formContent = new MultipartFormDataContent(); // 添加文件内容,参数名必须为"file"(api.video接口要求) var fileContent = new ByteArrayContent(fileBytes); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); formContent.Add(fileContent, "file", fileName); request.Content = formContent; var response = await client.SendAsync(request); // 打印响应内容方便排查问题 if (!response.IsSuccessStatusCode) { var errorMsg = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Upload failed: {errorMsg}"); } return response.IsSuccessStatusCode; } catch (Exception ex) { Console.WriteLine($"Failed to upload video: {ex.Message}"); return false; } }
额外注意事项:
- HttpClient超时设置:视频上传耗时较长,确保你的
HttpClient设置了足够长的超时时间,比如:client.Timeout = TimeSpan.FromMinutes(30); - 文件大小限制:确认api.video的文件大小限制(当前你设置的2GB符合官方免费版上限),如果超过限制会返回对应错误。
- 参数名验证:必须使用
file作为文件参数的名称,这是api.video接口强制要求的,不能修改。
内容的提问来源于stack exchange,提问作者Romain
相关产品推荐
相关产品推荐

