Загрузить изображение с URL, используя jQuery Ajax и PHP - PullRequest
0 голосов
/ 31 августа 2018

У меня есть URL для изображения и его необходимо загрузить на мой сервер.

JS код в HTML:

var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\/)|(\?v=|\&v=))([^#\&\?]*).*/;
var match = link.match(regExp);
var img = "http://i.ytimg.com/vi/"+match[8]+"/hqdefault.jpg";

jQuery.ajax({
    url: 'youtubeimages/upload.php',
    method: 'POST',
    data: img
});

upload.php:

<?php
    if($_FILES["file"]["name"] != '')
    {
     $test = explode('.', $_FILES["file"]["name"]);
     $ext = end($test);
     $name = rand(100, 999) . '.' . $ext;
     $location = './upload/' . $name;  
     move_uploaded_file($_FILES["file"]["tmp_name"], $location);
     echo '<img src="'.$location.'"/>';
    }
?>

Но не успех ... Как загрузить?

Или как передать эту ссылку img в этот php-скрипт?

<?php
$content = file_get_contents("U_R_L");
$fp = fopen("upload/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);
?>

1 Ответ

0 голосов
/ 02 сентября 2018

Хорошо. Я наконец создал "YouTube Thumbnail Downloader", но, пожалуйста, исправьте, если у вас есть другие хорошие идеи.

JS:

var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\/)|(\?v=|\&v=))([^#\&\?]*).*/;
var match = link.match(regExp);
var videoId = match[8];

jQuery.ajax({
    url: 'youtubeimages/upload.php',
    data: {videoId: videoId}
});

PHP:

<?php
$videoId = $_GET['videoId'];
$path_to_save_thumbnails = "";
$ch = curl_init();
$thubnail_types = array('hqdefault');

foreach($thubnail_types as $type) 
{
    $youtube_thumb_url = 'http://img.youtube.com/vi/'.$videoId.'/'.$type.'.jpg';

    curl_setopt($ch, CURLOPT_URL, $youtube_thumb_url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $image = curl_exec($ch);
    $info = curl_getinfo($ch);

    if($info['http_code'] == 200) {
        file_put_contents($path_to_save_thumbnails.$videoId.'.jpg', $image);
    }
}

curl_close($ch);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...