使用jQuery Ajax和PHP从URL上传图像

时间:2018-08-31 10:23:09

标签: php jquery ajax image upload

具有图片的网址,需要在我的服务器中上传。

HTML中的JS代码:

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 :(得分:0)

好的。我终于创建了“ YouTube缩略图下载器”,但是如果您有其他好主意,请更正。

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);