(400)无效的请求。除最终请求外,上传的字节数必须等于或大于262144

时间:2019-06-16 10:51:31

标签: youtube-api youtube-data-api

我试图在通过Data API V3上传视频后立即通过API设置自定义缩略图。

我遇到以下错误:

Error calling PUT https://www.googleapis.com/upload/youtube/v3/thumbnails/set?videoId=[VIDEOID]&key=[KEY]&uploadType=resumable&upload_id=[UPLOADID]: (400) Invalid request.  The number of bytes uploaded is required to be equal or greater than 262144, except for the final request (it's recommended to be the exact multiple of 262144).  The received request contained 8192 bytes, which does not meet this requirement.

上传的缩略图满足所有要求,例如 *长宽比为16:9 *尺寸为1280 * 720 *图片类型为png

                $thumbnailFile = $thumbnailFile;
                $client = new Google_Client();
                $youtube = new Google_Service_YouTube($client);
                $client->setAccessToken($accessToken);
                $io = new Google_IO_Stream($client);
                $io->setTimeout(180);
                if ($client->getAccessToken()) {

                    $imagePath = $thumbnailFile;
                    $headers = get_headers($imagePath, 1);

                    $file_size= $headers["Content-Length"];
                    $mime_type = null;
                    if($headers['Content-Type'] == 'image/png' || $headers['Content-Type'] == 'image/jpeg'){
                        $mime_type = $headers['Content-Type'];
                    }


                    $chunkSizeBytes = 1 * 1024 * 100;

                    $client->setDefer(true);
                    $params = array('videoId' => $videoId);

                    $setRequest = $youtube->thumbnails->set($videoId);

                    $media = new Google_Http_MediaFileUpload(
                        $client,
                        $setRequest,
                        $mime_type,
                        $file_size,
                        true,
                        false
                    );
                    $media->setFileSize($file_size);


                    $status = false;
                    $handle = fopen($imagePath, "rb");
                    while (!$status && !feof($handle)) {
                        $chunk = fread($handle, $chunkSizeBytes);
                        $status = $media->nextChunk($chunk);
                    }

                    fclose($handle);

                    $client->setDefer(false);

                    $status['code'] = 1;
                    $status['message'] = 'Thumbnail uploaded successfully';

2 个答案:

答案 0 :(得分:1)

setFileSize预计将传递您正在上传的实际文件的大小

在您的示例中,您先设置了$file_size= $headers["Content-Length"];,然后设置了$media->setFileSize($file_size);

请尝试更改为$media->setFileSize(filesize($imagePath));$file_size = filesize($imagePath);

答案 1 :(得分:0)

该错误似乎表明您的文件只有8.192KB,至少应为262.144KB