【问题标题】:Download a File and Upload it with PHP and AJAX下载文件并使用 PHP 和 AJAX 上传
【发布时间】:2011-11-20 08:59:22
【问题描述】:

我正在开发一个 Web 应用程序,它使用 JQuery AJAX 和 PHP 将一些数据上传到我的数据库中。

要提交的表单的其中一个字段是图像的 URL(WEB 的任何地址)。此图像应下载到我的 FTP 服务器,然后将其新地址插入数据库。

如何从任何 URL 下载图像并将其上传到我的 FTP 服务器?

表格:

<form id="form-id" method="post" action="insert.php" charset=utf-8">
    <input type="text" name="title" id="title">
    <input type="text" name="image-url" id="image-url">
    <input type="submit" name="submit" id="submit">
</form>

JavaScript

$("#submit").live("click", function(event){
    event.preventDefault();
    $.ajax({
        type : "POST",
        url : "insert.php",
        data : {
          'title': valueTitle,
          'image': valueImage
        },
        cache : false,
        success : function(html) {
        if (html == "success") {
            //...
        } else if (html == "ftp-error") {
            //...
        } else if (html == "sql-error") {
            //...
        }           
    }
    });     
});

插入.php

$title = $_REQUEST['title'];
$image = $_REQUEST['image'];

$imageInMyServer = downloadImageFromURLAndUploadFTP($image);
function downloadImageFromURLAndUploadFTP($image) {
    //that is what I want to know how to do.
}

//sql query with $title and $imageInMyServer

注意事项:

  • 我要下载的文件不在我的服务器上。它位于 Internet 的其他位置,我需要将其下载到我的 FTP 服务器
  • 没有。我无法在我的 SQL 查询中使用第一个外部 URL

【问题讨论】:

    标签: php ajax jquery ftp download


    【解决方案1】:

    这是how to do FTP transfers in PHP 上的一个很好的例子。至于下载文件,如果您使用的是 linux,则可以使用 wget(使用 exec() 函数)。

    exec('wget -q ' . $url . ' -0 /path/to/newfile');
    

    从我给你的链接中窃取代码 sn-p,你的函数可能如下所示:

    function downloadImageFromURLAndUploadFTP($image) {
        // in your case it would be some img extension like .jpg, .gif, or .png
        // you can check the extension of $image and use that if you want.
        $newFile = '/path/to/newfile.ext';
        exec('wget -q ' . $image . ' -0 ' . $newFile);
    
        if (file_exists($newFile)) {
            // set up connection and login
            $connect = ftp_connect($ftpServer); 
            $login   = ftp_login($connect, $ftpUser, $ftpPass); 
    
            // check connection
            if (!$connect || !$login) { 
                die('FTP connection has failed!'); 
            } else {
                echo "Connected to {$ftpServer}, for user {$ftpUser}";
            }
    
            // upload the file
            $fileNameOnFTPServer = 'whateverYouWantToNameIt.ext'; // arbitrary extension
            $upload = ftp_put($connect, $fileNameOnFTPServer, $newFile, FTP_BINARY); 
    
            // check upload status
            if (!$upload) { 
                echo "FTP upload has failed!";
            } else {
                echo "Uploaded {$image} to {$ftpServer} as {$fileNameOnFTPServer}";
            }
    
            ftp_close($connect);
        }
    }
    

    注意:当路径开始/ 时,有时file_exists() 的行为与我们预期的不同。例如/path/to/file 可能存在,但file_exists() 会认为它不存在,除非您删除开头的“/”。解决这个问题的一种方法是像这样检查它:

    file_exists(substr($newFile, 1))
    

    祝你好运!

    【讨论】:

      【解决方案2】:

      如果你没有 exec 权限,另一种解决方案是使用 curl 来抓取图像,或者你可以使用 file_get_contents(),方法很多,只是个人喜好。

      我整理了你的脚本可能是什么样子,我相信你可以改进它。

      插入.php

      <?php
      if(isset($_POST['image']) && isset($_POST['title'])){
          if(substr($_POST['image'],0,4)=='http'){
              $image = curlgetimage($_POST['image']);
              $info = pathinfo($_POST['image']);
              if(isset($info['extension']) && ($info['extension']=='gif' || $info['extension']=='png' || $info['extension']=='jpg')){
                  $path='./temp/'.md5($_POST['image']).'.'.$info['extension'];
                  file_put_contents($path,$image);
                  if(ftp_put_image($path)===true){
                      //Do your database stuff, remember to escape..
                      unlink($path);
                      echo 'Success';
                  }else{
                      echo 'ftp-fail';
                  }
              }else{
                  echo'File type not allowed';
              }
          }else{
              echo'Must start with http://';
          }
      }else{
          header('Location: http://www.example.com/');
      }
      
      
      function ftp_put_image($file){
          if(!file_exists($file)){return false;}
          $fp = fopen($file, 'r');
          $conn_id = ftp_connect('ftp.yourhost.com'); //change
          $login_result = ftp_login($conn_id,'username','password'); //change
          $return=(ftp_fput($conn_id, $file, $fp, FTP_BINARY))?true:false;
          ftp_close($conn_id);
          fclose($fp);
          return $return;
      }
      
      function curlgetimage($url) {
          $header[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
          $header[] = 'Connection: Keep-Alive';
          $header[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
          $curl = curl_init($url);
          curl_setopt($curl, CURLOPT_URL, $url);
          curl_setopt($curl, CURLOPT_USERAGENT, 'YourSpiderBot/0.01 (Bla Bla Robot; http://www.example.com; spider@example.com)'); //change
          curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
          curl_setopt($curl, CURLOPT_HEADER, 0);
          curl_setopt($curl, CURLOPT_REFERER, $url);
          curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
          curl_setopt($curl, CURLOPT_AUTOREFERER, true);
          curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($curl, CURLOPT_TIMEOUT, 60);
          $return = curl_exec($curl);
          curl_close($curl);
          return $return;
      }
      ?>
      

      【讨论】:

      • 我应该在 curl_setopt($curl, CURLOPT_USERAGENT, 'YourSpiderBot/0.01 (Bla Bla Robot; example.com; spider@example.com)') 上放什么?任何使用我的域或我必须使用特定值的东西?
      • 该文件永远不会被下载...所以我得到 FTP 错误文件不存在。我不知道是 curlgetimage($url) 没有下载它还是 file_put_contents($path,$image) 没有放它
      • @rlc 首先,您可以将任何东西作为用户代理,将自己展示为刮板/机器人很有礼貌,但您也可以伪装成普通浏览器。我确实使用表单而不是 `header('Location: example.com/');` 测试了该脚本默认情况下(只需取消注释一行),但 99% 的虚拟主机已启用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2014-05-02
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      相关资源
      最近更新 更多