Maison >interface Web >js tutoriel >Afficher la vignette de l'image Télécharger Ajax / PHP

Afficher la vignette de l'image Télécharger Ajax / PHP

Lisa Kudrow
Lisa Kudroworiginal
2025-03-04 01:09:13849parcourir

Afficher la vignette de l'image Télécharger Ajax / PHP

Afficher la vignette de l'image Télécharger Ajax / PHP MISE À JOUR 18/11/2012: La nouvelle version de ce téléchargement est maintenant ici JQUERY AJAX IMAGE Téléchargez l'exemple de vignette. C'est ainsi que vous pouvez ajouter un outil de téléchargement de fichiers / image sur vos formulaires et de faire stocker le fichier avec PHP et de renvoyer une version miniature à l'utilisateur pour afficher le formulaire. Bon.

Les plats clés

  • Utilisez AJAX avec PHP pour rationaliser le processus de téléchargement d'image, permettant un aperçu de la vignette en temps réel sans recharger la page.
  • Assurer l'expérience utilisateur transparent en implémentant les scripts jQuery qui gèrent le fichier télécharger dynamiquement et afficher instantanément les aperçus miniatures.
  • Incorporer les scripts PHP pour générer et retourner les URL miniatures au format JSON, facilitant l'intégration et la manipulation faciles du côté client.
  • Fournir une gestion complète des erreurs et des commentaires des utilisateurs pendant le processus de téléchargement pour maintenir des fonctionnalités robustes et l'engagement des utilisateurs.

comment cela fonctionne

  1. L'utilisateur sélectionne un fichier / image dans le champ de saisie du formulaire
  2. jQuery envoie une demande ajax avec le fichier / image
  3. PHP crée une version miniature et renvoie l'URL au format JSON
  4. jQuery affiche la version miniature sur le formulaire

Télécharger

  • jQuery4u-file-uploader-thumbnail.zip
  • doajaxfileupload.php
  • ajaxfileupload.php
  • jQuery.php
  • form-html.php
Télécharger la Source Filelese en direct Demo

Le code jQuery - jQuery.js

<span>/*******************************************************************
</span><span>  JS - PREVIEW IMAGE
</span><span>*******************************************************************/
</span><span>function previewImage(str) {
</span>	<span>//alert(str);
</span>	<span>ajaxFileUpload();
</span><span>}
</span>
<span>function removeImage() {
</span>	<span>//alert("Image Removed");
</span>	<span>$("#imagethumb").html('');
</span>	<span>$("#removebutton").hide();
</span>	<span>$("#supportedfiles").show();
</span>	<span>var tid = $("Input[name=allocatedimagename]").val();
</span>	<span>//remove the temporary image files created by the image
</span>	$<span>.get("/php/deleteblogthumb.php",{thumb_name: tid, type: 'js-blog'}, function(data){
</span>		<span>//alert(data);
</span>	<span>});
</span>
	<span>$("Input[name=allocatedimagename]").val('');
</span>	<span>$("Input[name=blogpic]").val('');
</span><span>}
</span>
<span>function ajaxFileUpload() {
</span>    <span>//starting setting some animation when the ajax starts and completes
</span>    <span>$("#Afficher la vignette de limage Télécharger Ajax / PHP")
</span>    <span>.ajaxStart(function(){
</span>        <span>$(this).show();
</span>    <span>})
</span>    <span>.ajaxComplete(function(){
</span>        <span>$(this).hide();
</span>    <span>});
</span>   
    <span>/*
</span><span>        prepareing ajax file upload
</span><span>        url: the url of script file handling the uploaded files
</span><span>                    fileElementId: the file type of input element id and it will be the index of  $_FILES Array()
</span><span>        dataType: it support json, xml
</span><span>        secureuri:use secure protocol
</span><span>        success: call back function when the ajax complete
</span><span>        error: callback function when the ajax failed
</span><span>       
</span><span>            */
</span>    $<span>.ajaxFileUpload
</span>    <span>(
</span>        <span>{
</span>            <span>url:'doajaxfileupload.php',
</span>            <span>secureuri:false,
</span>            <span>fileElementId:'blogpic',
</span>            <span>dataType: 'json',
</span>            <span>success: function (data<span>, status</span>)
</span>            <span>{
</span>                <span>if(typeof(data.error) != 'undefined')
</span>                <span>{
</span>                    <span>if(data.error != '')
</span>                    <span>{
</span>                        <span>alert(data.error);
</span>                    <span>}else
</span>                    <span>{
</span>                        <span>//alert(data.loc);
</span>                        <span>//show the preview of image
</span>						<span>var imageloc = '<span>Your uploaded image: <samp>'+data.name+'('+data.size+'kb)'+'</samp><br><img src="/static/imghwm/default1.png" data-src="'+data.loc+'" class="lazy"    style="max-width:90%"  style="max-width:90%" alt="your uploaded image"></span>';
</span>						<span>$("#imagethumb").html(imageloc); //add
</span>						<span>$("#removebutton").show();
</span>						<span>$("#supportedfiles").hide();
</span>						<span>//save the allocated image name for use with the process signup script
</span>						<span>$("Input[name=allocatedimagename]").val(data.loc);
</span>                    <span>}
</span>                <span>}
</span>            <span>},
</span>            <span>error: function (data<span>, status, e</span>)
</span>            <span>{
</span>                <span>alert(e);
</span>            <span>}
</span>        <span>}
</span>    <span>)
</span>   
    <span>return false;
</span>
<span>}</span>

Le code jQuery - ajaxfileupload.js

jQuery<span>.extend({
</span>
    <span>createUploadIframe: function(id<span>, uri</span>)
</span>	<span>{
</span>			<span>//create frame
</span>            <span>var frameId = 'jUploadFrame' + id;
</span>            
            <span>if(window.<span>ActiveXObject</span>) {
</span>                <span>var io = document.createElement('');
</span>                <span>if(typeof uri== 'boolean'){
</span>                    io<span>.src = 'javascript:false';
</span>                <span>}
</span>                <span>else if(typeof uri== 'string'){
</span>                    io<span>.src = uri;
</span>                <span>}
</span>            <span>}
</span>            <span>else {
</span>                <span>var io = document.createElement('iframe');
</span>                io<span>.id = frameId;
</span>                io<span>.name = frameId;
</span>            <span>}
</span>            io<span>.style.position = 'absolute';
</span>            io<span>.style.top = '-1000px';
</span>            io<span>.style.left = '-1000px';
</span>
            <span>document.body.appendChild(io);
</span>
            <span>return io			
</span>    <span>},
</span>    <span>createUploadForm: function(id<span>, fileElementId</span>)
</span>	<span>{
</span>		<span>//create form	
</span>		<span>var formId = 'jUploadForm' + id;
</span>		<span>var fileId = 'jUploadFile' + id;
</span>		<span>var form = $('');	
</span>		<span>var oldElement = $('#' + fileElementId);
</span>		<span>var newElement = $(oldElement).clone();
</span>		<span>$(oldElement).attr('id', fileId);
</span>		<span>$(oldElement).before(newElement);
</span>		<span>$(oldElement).appendTo(form);
</span>		<span>//set attributes
</span>		<span>$(form).css('position', 'absolute');
</span>		<span>$(form).css('top', '-1200px');
</span>		<span>$(form).css('left', '-1200px');
</span>		<span>$(form).appendTo('body');		
</span>		<span>return form;
</span>    <span>},
</span>
    <span>ajaxFileUpload: function(s) {
</span>        <span>// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
</span>        s <span>= jQuery.extend({}, jQuery.ajaxSettings, s);
</span>        <span>var id = new Date().getTime()        
</span>		<span>var form = jQuery.createUploadForm(id, s.fileElementId);
</span>		<span>var io = jQuery.createUploadIframe(id, s.secureuri);
</span>		<span>var frameId = 'jUploadFrame' + id;
</span>		<span>var formId = 'jUploadForm' + id;		
</span>        <span>// Watch for a new set of requests
</span>        <span>if ( s.global && ! jQuery.active++ )
</span>		<span>{
</span>			jQuery<span>.event.trigger( "ajaxStart" );
</span>		<span>}            
</span>        <span>var requestDone = false;
</span>        <span>// Create the request object
</span>        <span>var xml = {}   
</span>        <span>if ( s.global )
</span>            jQuery<span>.event.trigger("ajaxSend", [xml, s]);
</span>        <span>// Wait for a response to come back
</span>        <span>var uploadCallback = function(isTimeout)
</span>		<span>{			
</span>			<span>var io = document.getElementById(frameId);
</span>            <span>try 
</span>			<span>{				
</span>				<span>if(io.contentWindow)
</span>				<span>{
</span>					 xml<span>.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
</span>                	 xml<span>.responseXML = io.contentWindow.document.<span>XMLDocument</span>?io.contentWindow.document.<span>XMLDocument</span>:io.contentWindow.document;
</span>					 
				<span>}else if(io.contentDocument)
</span>				<span>{
</span>					 xml<span>.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
</span>                	xml<span>.responseXML = io.contentDocument.document.<span>XMLDocument</span>?io.contentDocument.document.<span>XMLDocument</span>:io.contentDocument.document;
</span>				<span>}						
</span>            <span>}catch(e)
</span>			<span>{
</span>				jQuery<span>.handleError(s, xml, null, e);
</span>			<span>}
</span>            <span>if ( xml || isTimeout == "timeout") 
</span>			<span>{				
</span>                requestDone <span>= true;
</span>                <span>var status;
</span>                <span>try {
</span>                    status <span>= isTimeout != "timeout" ? "success" : "error";
</span>                    <span>// Make sure that the request was successful or notmodified
</span>                    <span>if ( status != "error" )
</span>					<span>{
</span>                        <span>// process the data (runs the xml through httpData regardless of callback)
</span>                        <span>var data = jQuery.uploadHttpData( xml, s.dataType );    
</span>                        <span>// If a local callback was specified, fire it and pass it the data
</span>                        <span>if ( s.success )
</span>                            s<span>.success( data, status );
</span>    
                        <span>// Fire the global callback
</span>                        <span>if( s.global )
</span>                            jQuery<span>.event.trigger( "ajaxSuccess", [xml, s] );
</span>                    <span>} else
</span>                        jQuery<span>.handleError(s, xml, status);
</span>                <span>} catch(e) 
</span>				<span>{
</span>                    status <span>= "error";
</span>                    jQuery<span>.handleError(s, xml, status, e);
</span>                <span>}
</span>
                <span>// The request was completed
</span>                <span>if( s.global )
</span>                    jQuery<span>.event.trigger( "ajaxComplete", [xml, s] );
</span>
                <span>// Handle the global AJAX counter
</span>                <span>if ( s.global && ! --jQuery.active )
</span>                    jQuery<span>.event.trigger( "ajaxStop" );
</span>
                <span>// Process result
</span>                <span>if ( s.complete )
</span>                    s<span>.complete(xml, status);
</span>
                <span>jQuery(io).unbind()
</span>
                <span>setTimeout(function()
</span>									<span>{	try 
</span>										<span>{
</span>											<span>$(io).remove();
</span>											<span>$(form).remove();	
</span>											
										<span>} catch(e) 
</span>										<span>{
</span>											jQuery<span>.handleError(s, xml, null, e);
</span>										<span>}									
</span>
									<span>}, 100)
</span>
                xml <span>= null
</span>
            <span>}
</span>        <span>}
</span>        <span>// Timeout checker
</span>        <span>if ( s.timeout > 0 ) 
</span>		<span>{
</span>            <span>setTimeout(function(){
</span>                <span>// Check to see if the request is still happening
</span>                <span>if( !requestDone ) uploadCallback( "timeout" );
</span>            <span>}, s.timeout);
</span>        <span>}
</span>        <span>try 
</span>		<span>{
</span>           <span>// var io = $('#' + frameId);
</span>			<span>var form = $('#' + formId);
</span>			<span>$(form).attr('action', s.url);
</span>			<span>$(form).attr('method', 'POST');
</span>			<span>$(form).attr('target', frameId);
</span>            <span>if(form.encoding)
</span>			<span>{
</span>                form<span>.encoding = 'multipart/form-data';				
</span>            <span>}
</span>            <span>else
</span>			<span>{				
</span>                form<span>.enctype = 'multipart/form-data';
</span>            <span>}			
</span>            <span>$(form).submit();
</span>
        <span>} catch(e) 
</span>		<span>{			
</span>            jQuery<span>.handleError(s, xml, null, e);
</span>        <span>}
</span>        <span>if(window.attachEvent){
</span>            <span>document.getElementById(frameId).attachEvent('onload', uploadCallback);
</span>        <span>}
</span>        <span>else{
</span>            <span>document.getElementById(frameId).addEventListener('load', uploadCallback, false);
</span>        <span>} 		
</span>        <span>return {abort: function () {}};	
</span>
    <span>},
</span>
    <span>uploadHttpData: function( r<span>, type</span> ) {
</span>        <span>var data = !type;
</span>        data <span>= type == "xml" || data ? r.responseXML : r.responseText;
</span>        <span>// If the type is "script", eval it in global context
</span>        <span>if ( type == "script" )
</span>            jQuery<span>.globalEval( data );
</span>        <span>// Get the JavaScript object, if JSON is used.
</span>        <span>if ( type == "json" )
</span>            <span>eval( "data = " + data );
</span>        <span>// evaluate scripts within html
</span>        <span>if ( type == "html" )
</span>            <span>jQuery("").html(data).evalScripts();
</span>			<span>//alert($('param', data).each(function(){alert($(this).attr('value'));}));
</span>        <span>return data;
</span>    <span>}
</span><span>})
</span>
<span>The PHP Code – doajaxfileupload.php
</span>$ratio2<span>)	{
</span>          $thumb_w<span>=$new_w;
</span>          $thumb_h<span>=$old_y/$ratio1;
</span>        <span>}
</span>        <span>else	{
</span>          $thumb_h<span>=$new_h;
</span>          $thumb_w<span>=$old_x/$ratio2;
</span>        <span>}
</span>
          <span>// we create a new image with the new dimmensions
</span>        $dst_img<span>=<span>ImageCreateTrueColor</span>($thumb_w,$thumb_h);
</span>
        <span>// resize the big image to the new created one
</span>        <span>imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
</span>
        <span>// output the created image to the file. Now we will have the thumbnail into the file named by $filename
</span>        <span>if(!strcmp("png",$ext))
</span>          <span>imagepng($dst_img,$filename);
</span>        <span>else
</span>          <span>imagejpeg($dst_img,$filename);
</span>
          <span>//destroys source and destination images.
</span>        <span>imagedestroy($dst_img);
</span>        <span>imagedestroy($src_img);
</span>       <span>}
</span>
       <span>// This function reads the extension of the file.
</span>       <span>// It is used to determine if the file is an image by checking the extension.
</span>       <span>function getExtension($str) {
</span>               $i <span>= strrpos($str,".");
</span>               <span>if (!$i) { return ""; }
</span>               $l <span>= strlen($str) - $i;
</span>               $ext <span>= substr($str,$i+1,$l);
</span>               <span>return $ext;
</span>       <span>}
</span>
        <span>//reads the name of the file the user submitted for upAfficher la vignette de limage Télécharger Ajax / PHP
</span>       $image<span>=$_FILES[$fileElementName]['name'];
</span>
 	<span>// if it is not empty
</span> 	<span>if ($image)
</span> 	<span>{
</span> 		<span>// get the original name of the file from the clients machine
</span> 		$filename <span>= stripslashes($_FILES[$fileElementName]['name']);
</span>
 		<span>// get the extension of the file in a lower case format
</span> 	 	$extension <span>= getExtension($filename);
</span> 		$extension <span>= strtolower($extension);
</span> 		<span>// if it is not a known extension, we will suppose it is an error, print an error message
</span> 		<span>//and will not upload the file, otherwise we continue
</span> 		<span>if (($extension != "jpg")  && ($extension != "jpeg") && ($extension != "png"))
</span> 		<span>{
</span> 			$error <span>.= 'Unknown extension!';
</span> 			$errors<span>=1;
</span> 		<span>}
</span> 		<span>else
</span> 		<span>{
</span> 			<span>// get the size of the image in bytes
</span> 			<span>// $_FILES['image']['tmp_name'] is the temporary filename of the file in which
</span>			<span>//the uploaded file was stored on the server
</span> 			$size<span>=getimagesize($_FILES[$fileElementName]['tmp_name']);
</span> 			$sizekb<span>=filesize($_FILES[$fileElementName]['tmp_name']);
</span>
 			<span>//compare the size with the maxim size we defined and print error if bigger
</span> 			<span>if ($sizekb > MAX_SIZE*1024)
</span> 			<span>{
</span> 				$error <span>.= 'You have exceeded the size limit!';
</span> 				$errors<span>=1;
</span> 			<span>}
</span> 			<span>else {
</span>
              <span>//we will give an unique name, for example the time in unix time format
</span>            $image_name<span>=time().'.'.$extension;
</span>            <span>//the new name will be containing the full path where will be stored (images folder)
</span>            $newname<span>="/images/masters/".$image_name;
</span>            $copied <span>= copy($_FILES[$fileElementName]['tmp_name'], $newname);
</span>            <span>//we verify if the image has been uploaded, and print error instead
</span>            <span>if (!$copied)
</span>            <span>{
</span>              $error <span>.= 'Copy unsuccessfull!';
</span>              $errors<span>=1;
</span>            <span>}
</span>            <span>else
</span>            <span>{
</span>              <span>// the new thumbnail image will be placed in images/thumbs/ folder
</span>              $thumb_name<span>='/images/thumbs/thumb_'.$image_name;
</span>              <span>// call the function that will create the thumbnail. The function will get as parameters
</span>              <span>//the image name, the thumbnail name and the width and height desired for the thumbnail
</span>              $thumb<span>=make_thumb($newname,$thumb_name,40,40);
</span>
              <span>//also add the users pic
</span>              $thumb_name<span>='/images/thumbs/thumb_'.$image_name;
</span>              $thumb<span>=make_thumb($newname,$thumb_name,110,110);
</span>
            <span>}}
</span>        <span>}
</span> 			<span>}
</span>
      <span>//--------- END SECOND SCRIPT --------------------------------------------------------------------
</span>
      <span>//return variables to javascript
</span>			$filename <span>= $_FILES[$fileElementName]['name'];
</span>			$filesize <span>= round(($sizekb/1000), 0);
</span>			$fileloc <span>= $thumb_name;
</span>			<span>//for security reason, we force to remove all uploaded file
</span>			@<span>unlink($_FILES[$fileElementName]);
</span>	<span>}
</span>	$return_JSON <span>= "";
</span>	$return_JSON <span>.= "{";
</span>	$return_JSON <span>.=				"error: '" . $error . "',n";
</span>	$return_JSON <span>.=				"name: '" . $filename . "',n";
</span>	$return_JSON <span>.=				"size: '" . $filesize . "',n";
</span>	$return_JSON <span>.=				"loc: '" . $fileloc . "'n";
</span>	$return_JSON <span>.= "}";
</span>	echo $return_JSON<span>;
</span><span>?>
</span>
<span>The HTML Code
</span><span><label for="blogpic">Blog Thumbnail Picture:</label>
</span>          <span><input type="file" size="23" id="blogpic" name="blogpic" onchange="javascript:previewImage(this.value)">
</span>          <span><div id="preview-image">
              <span><div id="imagethumb"></div>
</span>              <span><input type="text" id="allocatedimagename" name="allocatedimagename">
</span>              <span><div id="Afficher la vignette de limage Télécharger Ajax / PHP" style="visibility:hidden"><img src="/images/Afficher%20la%20vignette%20de%20limage%20T%C3%A9l%C3%A9charger%20Ajax%20/%20PHP.gif" alt="Afficher la vignette de limage Télécharger Ajax / PHP" title="Afficher la vignette de limage Télécharger Ajax / PHP"></div>
</span>              <span><div id="supportedfiles"><p class="nomargin">Supported file types: jpg, jpeg, png (max 1mb) <br>Your image will be resized to 110 by 110 px (40 by 40 for blog thumbs)</p></div>
</span>
              <span><div id="removebutton"><button id="buttonremove" onclick="javascript:removeImage()"></button></div>
</span>          <span></span>
</div>
</span>        <span>
</span>


<span>Frequently Asked <span>Questions</span> (FAQs) about Thumbnail Image Upload with AJAX/PHP
</span>


<span>How can I handle multiple image uploads using AJAX/PHP? Handling multiple image uploads using AJAX/PHP is quite similar to handling a single image upload. <span>The</span> main difference is that you need to loop through the array of files in the $_FILES superglobal. <span>For</span> each file, you can perform the same validation and upload process as you would for a single file. <span>Remember</span> to adjust your HTML form to allow multiple file selection by adding the ‘multiple’ attribute to your input tag.  <span>How</span> can I display a progress bar during the image upload? To display a progress bar during the image upload, you can use the ‘progress’ event of the XMLHttpRequest object. <span>This</span> event is triggered periodically during the upload process, and you can use it to calculate the percentage of the upload that has been completed and update your progress bar accordingly.  <span>How</span> can I resize the uploaded image before saving it to the server? Resizing the uploaded image before saving it to the server can be done using PHP’s GD library or ImageMagick. <span>These</span> libraries provide functions to create a new image with the desired dimensions and copy the uploaded image into it, effectively resizing it. <span>Remember</span> to adjust the quality of the image to avoid losing too much detail during the resizing process.  <span>How</span> can I handle errors during the image upload process? Handling errors during the image upload process is crucial to provide a good user experience. <span>You</span> can check for errors by inspecting the ‘error’ property of the file in the $_FILES superglobal. <span>This</span> property will be 0 if no error occurred, and a different value otherwise. <span>You</span> can then use a switch statement to handle each possible error code and provide a meaningful error message to the user.  <span>How</span> can I restrict the types of images that can be uploaded? Restricting the types of images that can be uploaded can be done by checking the ‘type’ property of the file in the $_FILES superglobal. <span>This</span> property contains the MIME type of the file, which you can compare with the allowed types (e.g., ‘image/jpeg’, ‘image/png’, etc.). <span>If</span> the file’s type is not in the list of allowed types, you can reject the upload and provide an error message to the user.  <span>How</span> can I secure my image upload script against attacks? Securing your image upload script against attacks is crucial to prevent unauthorized access to your server. <span>You</span> can do this by validating the uploaded file thoroughly, checking its size, type, and content, and rejecting any file that doesn’t meet your criteria. <span>You</span> should also rename the uploaded file to a random name to prevent attackers from overwriting existing files or executing arbitrary code on your server.  <span>How</span> can I limit the size of the uploaded images? Limiting the size of the uploaded images can be done by checking the ‘size’ property of the file in the $_FILES superglobal. <span>This</span> property contains the size of the file in bytes, which you can compare with your maximum allowed size. <span>If</span> the file’s size is larger than the allowed size, you can reject the upload and provide an error message to the user.  <span>How</span> can I store the uploaded images in a database? Storing the uploaded images in a database can be done by saving the path to the image in a database table. <span>You</span> should not store the image data itself in the database, as this can quickly fill up your database and degrade its performance. <span>Instead</span>, save the image to a directory on your server and store the path to this file in your database.  <span>How</span> can I display the uploaded images on my website? Displaying the uploaded images on your website can be done by retrieving the paths to the images from your database and using them in the ‘src’ attribute of ‘img’ tags. <span>Remember</span> to sanitize the paths before outputting them to prevent cross-site scripting (XSS) attacks.  <span>How</span> can I delete uploaded images from the server? Deleting uploaded images from the server can be done using the ‘unlink’ function in PHP. <span>This</span> function deletes a file from the server. <span>You</span> should also remove the path to the image from your database to keep it in sync with the file system.  
</span>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn