Вы должны предоставить читаемый файл в Twitter API для загрузки видео в laravel [закрыто]Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Вы должны предоставить читаемый файл в Twitter API для загрузки видео в laravel [закрыто]

Сообщение Anonymous »

Я пытаюсь загрузить видео в Твиттер, я делаю это в три этапа, как документация в запросе инициализации, затем добавляю видео частями, хорошо, а перед этим я сохраняю файл на своем локальном сервере в папке хранения, и файл фактически попадает туда правильно, но в процессе добавления выдается это сообщение об ошибке

Код: Выделить всё

{
"message": "Failed to append video chunk",
"error": "You must supply a readable file"
и это мой код

Код: Выделить всё

   $twitter = new TwitterOAuth(
config('services.twitter.client_id'),
config('services.twitter.client_secret'),
$accessToken,
$accessTokenSecret
);

// Increase the timeout settings
$twitter->setTimeouts(30, 300); // Set the connect timeout to 30 seconds and the request timeout to 300 seconds

// Tell the library we want to use the v1.1 API for media upload
$twitter->setApiVersion('1.1');

if ($request->hasFile('video')) {
$videoFile = $request->file('video');

// Store file in storage/app/public/temp

// Store file in storage/app/public/temp
$path = $videoFile->store('temp', 'public');
$fullPath = storage_path('app/public/' .  $path);

// Ensure the file is uploaded to the local server
if (!file_exists($fullPath)) {
return response()->json([
"message" => "Failed to upload video to local server"
], 500);
}

// Use the file path for further processing

$videoMimeType = $videoFile->getMimeType();
$videoSize = $videoFile->getSize();

// Initialize upload
$initResponse = $twitter->upload('media/upload', [
'command' => 'INIT',
"media" => $fullPath,
'media_type' => $videoMimeType,
'total_bytes' => $videoSize,
'media_category' => 'tweet_video'
]);

if (!isset($initResponse->media_id_string)) {
// Clean up temp file
unlink($fullPath);
return response()->json([
"message" => "Failed to initialize video upload",
"error" => $initResponse
], 500);
}

$mediaId = $initResponse->media_id_string;

// Append chunks
$segmentIndex = 0;
$chunkSize = 5 * 1024 * 1024; // 5MB chunks
$handle = fopen($fullPath, 'rb');

try {
while (!feof($handle)) {
$chunk = fread($handle, $chunkSize);
$appendResponse = $twitter->upload('media/upload', [
'command' => 'APPEND',
'media_id' => $mediaId,
'segment_index' => $segmentIndex,
'media' => base64_encode($chunk)
]);

if ($appendResponse !== true) {
throw new \Exception(json_encode($appendResponse));
}

$segmentIndex++;
}
} catch (\Exception $e) {
fclose($handle);
unlink($fullPath);
return response()->json([
"message" => "Failed to append video chunk",
"error" => $e->getMessage()
], 500);
}

fclose($handle);
unlink($fullPath);

// Finalize the upload
$finalizeResponse = $twitter->upload('media/upload', [
'command' => 'FINALIZE',
'media_id' => $mediaId
]);

if (isset($finalizeResponse->media_id_string)) {

return response()->json([
"message" => "Video uploaded successfully",
"media_id" => $finalizeResponse->media_id_string
], 200);
} else {

return response()->json([
"message" => "Failed to finalize video upload",
"error" => $finalizeResponse
], 500);
}
} else {

return response()->json(["message" => "No video file provided"], 400);
}
}
и это значение переменной $fullPath: C:\xampp\htdocs\ThePostFlex\storage\app/public/temp/SkLhzo61v1bQnWS6giePxCOZvboVf6A1WvXPuiVW.mp4
Пожалуйста, срочно нужна помощь. спасибо

Подробнее здесь: https://stackoverflow.com/questions/793 ... in-laravel
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»