Я пытаюсь загрузить видео в Твиттер, я делаю это в три этапа, как документация в запросе инициализации, затем добавляю видео частями, хорошо, а перед этим я сохраняю файл на своем локальном сервере в папке хранения, и файл фактически попадает туда правильно, но в процессе добавления выдается это сообщение об ошибке
{
"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
Вы должны предоставить читаемый файл в Twitter API для загрузки видео в laravel [закрыто] ⇐ Php
Кемеровские программисты php общаются здесь
1736629746
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
Подробнее здесь: [url]https://stackoverflow.com/questions/79342733/you-must-supply-a-readable-file-in-twitter-api-video-upload-in-laravel[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия