javascript - 如何在选择文件后立即上传图像,而不是强制用户单击单独的 "Upload"按钮?

标签 javascript php jquery ajax image-uploading

我有一个图像上传表单,您可以在其中单击“选择图像”,然后它会弹出文件选择窗口。您选择一个图像,然后文件名出现在屏幕上(还不是图像,只是文件名),旁边还有一个新出现的“上传”按钮。然后你必须点击“上传”才能使图像真正上传并出现在预览 Pane 中。

我很想压缩这个过程,这样当有人单击“选择图像”并选择他们想要上传的图像时,它就会删除中间人并立即上传图像并在预览 Pane 中向他们显示图像。为什么让用户必须点击“上传”?

我在下面包含了相关代码。有没有办法调整我现有的代码,使上传部分在选择文件后立即发生?或者我可能需要从头开始做我想做的事吗?

图片上传表单:

<li class="section">
            <label class="caption" for="">Pool Image </label> (OPTIONAL - You can add one later if you don't have one now)<br>           
            <div id="preview"><img id="image" src="images/no-image.png" /></div>
            <label for="uploadImage" id="custom-file-upload">
                Choose Image
            </label>
            <span id="file-selected"></span>
            <input id="uploadImage" type="file" accept="image/*" name="image" />
            <input id="button" type="button" value="Upload" class="displaynone webkit">
            <input id="remove-image" class="displaynone" type="button" value="Remove/Change">
            <div id="err"></div>
            </li>
            <li class="section">
            <a class="goback" id="cancel-and-remove-image" href='/my-pools'>&laquo; Cancel</a>
            <input type="submit" name="submit"  class="submit" value="Create Pool &raquo;" />
            </li>

页面上也有这个JS:

$(document).ready(function () {
    $("input:file").change(function (){
      $( "#button" ).show();
     });

 $('#uploadImage').on('change', function() { var fileName = ''; fileName = $(this).val(); $('#file-selected').html(fileName); });

 $("#button").click(function(){
    var imageData = new FormData();
    imageData.append('image', $('#uploadImage')[0].files[0]);

    //Make ajax call here:
    $.ajax({
          url: '/upload-image-ajax.php',
          type: 'POST',
          processData: false, // important
          contentType: false, // important
          data: imageData,
          beforeSend : function()  {
            $("#err").fadeOut();
           },
       success: function(result) {
            if(result=='invalid file') {
             // invalid file format.
             $("#err").html("Invalid File. Image must be JPEG, PNG or GIF.").fadeIn();
            } else {

             // view uploaded file.
             $("#image").attr('src', '/'+result);
            /* $("#preview").html(data).fadeIn();*/
            /* $("#form")[0].reset(); */
             //show the remove image button
             $('#file-selected').empty();
             $( "#remove-image" ).show();
             $( "#custom-file-upload" ).hide();
             $( "#uploadImage" ).hide();
             $( "#button" ).hide();
            }
          },
         error: function(result)  {
              $("#err").html("errorcity").fadeIn();
          }      
     });
   });

  $("#remove-image").click(function(){
    //Make ajax call here:
    $.ajax({
          url: "/remove-image.php",
          type: 'POST',
          processData: false, // important
          contentType: false, // important
       success: function(result) {
            if(result=='gone') {
             $("#image").attr('src', '/images/no-image.png');
             $('#file-selected').empty();
             $( "#custom-file-upload" ).show();
             $( "#remove-image" ).hide();
             $( "#uploadImage" ).hide();
             $( "#button" ).hide();
            } else {
                $("#err").html("sorry"+result).fadeIn();
            }
          },
         error: function(result)  {
              $("#err").html("error").fadeIn();
          }      
     });
   });

  });

这是 AJAX 调用的 PHP 脚本(即 upload-image-ajax.php):

<?php
require_once("includes/session.php");
$poolid=strtolower($_SESSION['poolid']); //lowercase it first so we get exact matches
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

if(isset($_FILES['image'])) {
    $img = $_FILES['image']['name'];
    $tmp = $_FILES['image']['tmp_name'];

    // get uploaded file's extension
    $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

    //checking if image exists for this pool and removing if so, before adding new image in its place
    if(file_exists("uploads/".$poolid.".png")) {
     unlink("uploads/".$poolid.".png");
    }

    // checks valid format
    if(in_array($ext, $valid_extensions))  { 
    //re-size the image and make it a PNG before sending to server
    $final_image = $poolid . ".png";
    $path = "uploads/".strtolower($final_image); 
    $size = getimagesize($tmp);
    $ratio = $size[0]/$size[1]; // width/height
    if( $ratio > 1) {
        $width = 200;
        $height = 200/$ratio;
    }
    else {
        $width = 200*$ratio;
        $height = 200;
    }
    $src = imagecreatefromstring(file_get_contents($tmp));
    $dst = imagecreatetruecolor($width,$height);
    imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
    imagedestroy($src);
    imagepng($dst, $path); // adjust format as needed
    imagedestroy($dst);
    $_SESSION['image_uploaded']="yes";
    echo $path ."?".rand(1,32000); 
    } else {
      echo 'invalid file';
    }
}
?>

最佳答案

只需在文件输入 change 事件中添加图像上传 AJAX 调用即可。这应该在用户选择图像后立即上传您的图像。

$(document).ready(function() {

  $('#uploadImage').on('change', function() {

    var fileName = '';
    fileName = $(this).val();
    $('#file-selected').html(fileName);


    var imageData = new FormData();
    imageData.append('image', $('#uploadImage')[0].files[0]);

    //Make ajax call here:
    $.ajax({
      url: '/upload-image-ajax.php',
      type: 'POST',
      processData: false, // important
      contentType: false, // important
      data: imageData,
      beforeSend: function() {
        $("#err").fadeOut();
      },
      success: function(result) {
        if (result == 'invalid file') {
          // invalid file format.
          $("#err").html("Invalid File. Image must be JPEG, PNG or GIF.").fadeIn();
        } else {

          // view uploaded file.
          $("#image").attr('src', '/' + result);
          /* $("#preview").html(data).fadeIn();*/
          /* $("#form")[0].reset(); */
          //show the remove image button
          $('#file-selected').empty();
          $("#remove-image").show();
          $("#custom-file-upload").hide();
          $("#uploadImage").hide();
          $("#button").hide();
        }
      },
      error: function(result) {
        $("#err").html("errorcity").fadeIn();
      }
    });

  });

});

关于javascript - 如何在选择文件后立即上传图像,而不是强制用户单击单独的 "Upload"按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509032/

相关文章:

javascript - 加上javascript中带引号的运算符

php - 数据库不存在。但它确实

PHP:更清晰的分页 url(文件夹)

javascript - 当前页面上的行数?

javascript - 为什么这个圆圈内的球不能正常弹跳?

javascript - 从 java 文件中的函数弹出简单的文本消息警报

php包含语句

javascript - 一次仅将 jquery 脚本应用于一个类

Javascript 对话框的使用

javascript - 在单击事件处理程序中延迟 window.open