簡體   English   中英

選擇文件后如何立即上傳圖像,而不是強制用戶單擊單獨的“上傳”按鈕?

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

我有一個圖像上傳表單,您單擊“選擇圖像”,它會顯示文件選擇 window。 您選擇一個圖像,然后文件名出現在屏幕上(不是圖像,只是文件名),旁邊是一個新出現的“上傳”按鈕。 然后您必須點擊“上傳”才能使圖像真正上傳並出現在預覽窗格中。

我很想壓縮這個過程,這樣當有人點擊“選擇圖像”並選擇他們想要上傳的圖像時,它會移除中間人並立即上傳圖像並在預覽窗格中向他們顯示圖像。 為什么讓用戶必須點擊“上傳”?

我在下面包含了我的相關代碼。 有沒有辦法調整我現有的代碼以使上傳部分在文件選擇后立即發生? 還是我可能需要從頭開始做我想做的事?

圖片上傳表格:

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

您可以通過使用ajax或調用表單的Submit事件來調用將執行此操作的函數。

要調用此函數,請在文件/ img標簽中放置一個onchange事件(僅當使用img顯示所選圖像的預覽時才使用img)

這不是一個完整的答案,因為如果用戶改變主意並想要上傳另一張圖像,同時最初選擇的圖像已經自動上傳到任何服務器並且不再需要,所以它是陳舊和無用的,對嗎?

我覺得你應該提到它以某種方式被刪除,因為服務器空間不是免費的,以及它是如何被刪除的等等,恕我直言♂️

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM