简体   繁体   English

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

[英]How to upload image immediately after file is selected, rather than force user to click separate "Upload" button?

I have an image upload form where you click "Choose Image" and it brings up the file selection window.我有一个图像上传表单,您单击“选择图像”,它会显示文件选择 window。 You choose an image and then the filename appears on the screen (not the image yet, just the filename) alongside a newly appeared "Upload" button.您选择一个图像,然后文件名出现在屏幕上(不是图像,只是文件名),旁边是一个新出现的“上传”按钮。 Then you have to hit "Upload" to make the image truly upload and appear in the preview pane.然后您必须点击“上传”才能使图像真正上传并出现在预览窗格中。

I would love to condense this process so that when someone clicks "Choose Image" and selects the image they want to upload, it removes the middle man and immediately uploads the image and shows them the image in the preview pane.我很想压缩这个过程,这样当有人点击“选择图像”并选择他们想要上传的图像时,它会移除中间人并立即上传图像并在预览窗格中向他们显示图像。 Why make the user have to click "Upload"?为什么让用户必须点击“上传”?

I've included my related code below.我在下面包含了我的相关代码。 Is there a way to tweak my existing code to make the upload part happen immediately after file selection?有没有办法调整我现有的代码以使上传部分在文件选择后立即发生? Or do I likely need to start from scratch to do what I want?还是我可能需要从头开始做我想做的事?

Image upload form:图片上传表格:

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

This JS is also on the page:这个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();
          }      
     });
   });

  });

This is the PHP script that AJAX calls (ie upload-image-ajax.php ):这是 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';
    }
}
?>

Just add your image upload AJAX call inside the file input change event. 只需在文件输入change事件中添加图片上传AJAX调用即可。 This should upload your image right after user selects the image. 用户选择图片后,这应该立即上传您的图片。

 $(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(); } }); }); }); 

You can invoke a function that will do so by using either ajax or invoke form's submit event. 您可以通过使用ajax或调用表单的Submit事件来调用将执行此操作的函数。

To invoke this function put a onchange event in the file/img tag (use img only if img is used to show the preview of the selected image) 要调用此函数,请在文件/ img标签中放置一个onchange事件(仅当使用img显示所选图像的预览时才使用img)

Code

This is not a complete answer cause what if user changes their mind and wants to upload another image instead meanwhile the initial selected one has already automatically uploaded to whatever server and not needed again so it is stale and useless right?这不是一个完整的答案,因为如果用户改变主意并想要上传另一张图像,同时最初选择的图像已经自动上传到任何服务器并且不再需要,所以它是陈旧和无用的,对吗?

I feel you should mention it gets deleted somehow as server space is not free and how it gets deleted etc with all due respect ♂️我觉得你应该提到它以某种方式被删除,因为服务器空间不是免费的,以及它是如何被删除的等等,恕我直言♂️

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM