תחי ישראל - אין לנו ארץ אחרת

תחי ישראל -אין לנו ארץ אחרת

העלאת קובץ תמונה באמצעות jQuery ו-PHP

מחבר:
בתאריך:

במדריך זה קוד פשוט להעלאת תמונה באמצעות jQuery ו-PHP.

 

ההטמ"ל

כולל כפתור theTrigger, שלחיצה עליו מפעילה את הסקריפט שמעלה את התמונה. הסקריפט מחקה את הקלקה על שדה file (להעלאת קבצים), והתמונה מוצגת בתוך אלמנט התמונה theImage.

<img src="/placeholder.jpg" id="theImage">		

<button id="theTrigger">Upload file</button>

<input type="file" id="file" style="display:none"/>

 

קוד ה-jQuery

לחיצה על כפתור, גורמת להפעלת מתודה שמעלה את התמונה לצד השרת, ומציגה את התמונה שעלתה למשתמש

(function($){
  // Limit the allowed file size
  var imgSizeLimit = 2*1024*1024;

  // The FileList object represents the files uploaded with the file upload button.
  //  It contains the data for the name, size, extension and content of the files
  function uploadImage() {
     // Get the file input field
     var img = $("#file");

    // Get the uploaded file
    var file = img[0].files[0];

    // Validations
    if(file.size > imgSizeLimit){
        alert("התמונה גדולה מדי");
        return;
    }

    if(file.type !== 'image/png' && file.type !== 'image/jpg' && file.type !== 'image/jpeg'){
        alert("נא להעלות תמונה מסוג jpeg או png");
        return;
    }
            
      // The FileReader object lets apps read asynchronously the contents of files
      var r = new FileReader();
			
      // Fire after the reading of the file ended
      r.addEventListener("load", function(e) {
        // Send the data with AJAX to the server and get the response
        $.post('/create_new_img.php', {'f': e.target.result}, function(res){
          res = JSON.parse(res);
          if(res.success === true){
               $("#theImage").attr('src', res.path);
          } else {
              alert("בעיה בהעלאת התמונה");
          }
        });
      });
      // Read the content of the file
      r.readAsDataURL(file);
  }
	
  // Listens to any change to the #file element
  //  then fires the uploadImage function
  //  that receives the files property
  $("#file").on("change", function(){
    uploadImage();
  });

  // Clicking #theTrigger button triggers clicking
  //  the #file element
  $("#theTrigger").on("click", function(){
    $("#file").trigger("click");
  });
}(jQuery));

הקלקה על האלמנט theTrigger גורמת להפעלה לחיקוי של תוצאת הלחיצה על שדה file להעלאת קבצים על ידי המתודה trigger של jQuery.

ההקלקה על שדה ה-file קוראת לפונקציה uploadImage

הפונקציה ממצה את המידע שמכיל שדה בטופס מסוג file.

הפונקציה מוודאת שהקובץ מתאים לסוג הקובץ שאנחנו מצפים לו (בקוד להלן, קובץ תמונה) וגם שהקובץ אינו גדול מדי (בדוגמה, 2Mb).

במידה ועבר את הבדיקה, תוכנו של הקובץ נקרא על ידי האובייקט FileReader, ואחרי שהקריאה מסתיימת נשלח המידע ב-Ajax לצד השרת.

במידה וצד השרת מחזיר אינדיקציה על כך שהקובץ עלה בהצלחה, התמונה תשובץ במקום הדיב מחזיק המקום.

 

קוד ה-PHP

קולט את המידע שנשלח מצד המשתמש. מוודא את גודל הקובץ ואת סוגו באמצעות הפונקציה getimagesize. משתמש ב-base64_decode כדי להמיר את הקובץ, והופך את זרם המידע לתמונה ממש על ידי הפונקציה file_put_contents.

<?php
if(!isset($_POST['f']) || empty($_POST['f'])) exit;

// Define the upload folder	
$destinationFolder = $_SERVER['DOCUMENT_ROOT'] . "/uploads/";	

// Maximum allowed size
$maxFileSize = 2*1024*1024;	// kb


// GET the posted data	
$file = $_POST['f'];

// getimagesize is used to get the file extension
// Only png / jpg mime types are allowed
$size = getimagesize ($file);
$ext  = $size['mime'];
if($ext == 'image/jpeg')
	$ext = '.jpg';
elseif($ext == 'image/png')
	$ext = '.png';
else
	exit(json_encode(['success'=>false, 'reason'=>'only png and jpg mime types are allowed'])); 

// Prevent the upload of large files
if(strlen(base64_decode($file)) > $maxFileSize)
	exit(json_encode(['success'=>false, 'reason'=>"file size exceeds {$maxFileSize} Mb"])); 

// Remove inline tags and spaces
$img = str_replace('data:image/png;base64,', '', $file);
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);

// Read base64 encoded string as an image
$img = base64_decode($img);

// Give the image a unique name. Don't forget the extension
$filename = date("d_m_Y_H_i_s")."-".time().$ext;

// The path to the newly created file inside the upload folder
$destinationPath = "$destinationFolder$filename";

// Create the file or return false
$success = file_put_contents($destinationPath, $img);

if(!$success) 
	exit(json_encode(['success'=>false, 'reason'=>'the server failed in creating the image']));

// Inform the browser that everything worked
exit(json_encode(['success'=>true,'path'=>'/uploads/'.$filename]));

 

לכל מדריכי ה-jQuery

 

אהבתם? לא אהבתם? דרגו!

0 הצבעות, ממוצע 0 מתוך 5 כוכבים

 

 

המדריכים באתר עוסקים בנושאי תכנות ופיתוח אישי. הקוד שמוצג משמש להדגמה ולצרכי לימוד. התוכן והקוד המוצגים באתר נבדקו בקפידה ונמצאו תקינים. אבל ייתכן ששימוש במערכות שונות, דוגמת דפדפן או מערכת הפעלה שונה ולאור השינויים הטכנולוגיים התכופים בעולם שבו אנו חיים יגרום לתוצאות שונות מהמצופה. בכל מקרה, אין בעל האתר נושא באחריות לכל שיבוש או שימוש לא אחראי בתכנים הלימודיים באתר.

למרות האמור לעיל, ומתוך רצון טוב, אם נתקלת בקשיים ביישום הקוד באתר מפאת מה שנראה לך כשגיאה או כחוסר עקביות נא להשאיר תגובה עם פירוט הבעיה באזור התגובות בתחתית המדריכים. זה יכול לעזור למשתמשים אחרים שנתקלו באותה בעיה ואם אני רואה שהבעיה עקרונית אני עשוי לערוך התאמה במדריך או להסיר אותו כדי להימנע מהטעיית הציבור.

שימו לב! הסקריפטים במדריכים מיועדים למטרות לימוד בלבד. כשאתם עובדים על הפרויקטים שלכם אתם צריכים להשתמש בספריות וסביבות פיתוח מוכחות, מהירות ובטוחות.

המשתמש באתר צריך להיות מודע לכך שאם וכאשר הוא מפתח קוד בשביל פרויקט הוא חייב לשים לב ולהשתמש בסביבת הפיתוח המתאימה ביותר, הבטוחה ביותר, היעילה ביותר וכמובן שהוא צריך לבדוק את הקוד בהיבטים של יעילות ואבטחה. מי אמר שלהיות מפתח זו עבודה קלה ?

השימוש שלך באתר מהווה ראייה להסכמתך עם הכללים והתקנות שנוסחו בהסכם תנאי השימוש.

הוסף תגובה חדשה

 

 

ענה על השאלה הפשוטה הבאה כתנאי להוספת תגובה:

איך אומרים בעברית אינטרנט?

 

תמונת המגיב

מושיקו בתאריך: 29.07.2019

כשניסיתי להעלות תמונה קיבלתי הודעת שגיאה Uncaught ReferenceError: uploadImages is not defined

תמונת המגיב

יוסי בן הרוש בתאריך: 29.07.2019

אתה צודק. החלפתי את שם הפונקציה ל - uploadImage.