Partage
  • Partager sur Facebook
  • Partager sur Twitter

Upload Fichier Ajax

Iframe calcul du temps d'execution

    15 janvier 2011 à 20:50:28

    hello,
    je suis en train de réaliser un petit script js avec mootools-1.3 qui me permet d'uploader des fichiers
    par le biais d'une Iframe, j'essaie de trouver une astuce pour récupérer le temps que met le fichier à être uploader
    J'arrive à calculé le temps d'exécution du script mais je voudrais afficher le chrono en temps réel
    mais là ça bloque au moment où l'iframe se charge. Pas facile à expliquer avec des mots.
    du code y en a pas mal ne prenez pas peur :D :
    Class Uploader :

    /**
     * Popup de téléchargement par Iframe Ajax
     * @author franckysolo
     * @since 14/01/2011 
     * @with Mootools 1.3
     */
    var IndyPopUploader = new Class({
    	
     	Implements : [Options, Events],
     	options :{
     		url : 'ajax/uploader.php',
     		container : 'indyloader',
     		button : 'sending',
     		title : 'Gestionnaire d\'envoi d\'images',
     		dirs : ['mp', 'forum', 'news', 'cours']	 		
     	},
     	
     	initialize : function(){	
     		this.container = $(this.options.container);	 		
     		this.drag = new Drag(this.container);
     		this.button = $(this.options.button);
     		this.isOpen = true;
     		this.isResize = true;
     		this.url = this.options.url;		
     		this.setForm();
     		this.setScreen();
     		this._setDirBox(this.options.dirs);		
     		this.setTitle(this.options.title);
     		this._setWindowPopUp();	
     		this._buildForm();	
     		this.timer = 0;
     		this.counter = 0;
     		this.container.fade('hide');
     		$('testing').set('html',this.counter);	
     		this.prev = new Element('p', { html : '',
    			styles : {
    				color : 'green',
    				'font-style' : 'italic'
    			}
    		});
     	},
     	
     	setFrame : function() {
     		this.frame = new IFrame({
    			src : '#', id : 'up-frame', name : 'up-frame',
    			styles : {
    				border : '5px solid red',
    				width : 300,
    				height : 50
    			}
    		});
     		this.frame.addEvent('load', function(){
     			this.prev.set('html', 'Fichier envoyé en '+ this.getChrono());
    			this.counter = 0;
    			alert('completed!!!');
    			clearTimeout(this.timer);
     		}.bind(this));
     	},
     	setForm : function(){
     		this.formUpload = new Element('form',{
     			id : 'up-form',
     			enctype : 'multipart/form-data',
     			action : 'ajax/upload.php',
     			method : 'post',
     			target : 'up-frame',
     			name : 'up-form',
     			styles : {
     				margin : 'auto',
    		 		padding: '2%',
    		 		border: '1px solid #eee',
    		 		width : '95.5%',
    		 		float: 'left',
    		 		color: 'white',
    		 		'font-weight': 'bold'
     			}
     		}).addEvent('submit', function(){
     			alert('running...');
     			this.upload();
     			this.timer = this.setTimer.periodical(10, this);
     			this.prev.set('html', 'Fichier envoyé '+this.getChrono());
     		}.bind(this));
     	},
     	
     	setTimer : function(){
     		this.counter++;	
     	},
     	
     	getChrono : function(){
     		var ms = Math.floor( ( (this.counter / 60) - Math.floor(this.counter / 60) ) * 60 );
     		var s =  Math.floor( ( (this.counter / 3600) - Math.floor(this.counter / 3600) ) * 60 ); 
     		if( ms % 60 == 0 ) {
     			ms = 0;
    		}
     		if( s % 60 == 0 ) {
     			s = 0;
    		}
     		ms = ( ms < 10 ) ? "0"+ms : ms;
    		s = ( s < 10 ) ? "0"+s : s;
    		return ms + 's : ' + s + ' ms';
     	},
     	
    	upload : function(){
    		this.setFrame();
    		this.prev.inject(this.setCompactBox().inject(this.formUpload));
    		this.frame.inject(this.formUpload);	
     	},
     	
     	setScreen : function(){
     		this.screen = new Element('input', {
     			 type : 'text',
     			 name : 'dir',
     			 'readonly' : 'readonly',
     			 size : '5'
     		});
     	},
     	
     	setCloser : function() {
     		this.closer = new Element('img',{
     			id : 'closer',
     			src : 'pub/img/popclose.gif',
     			width : 16,
     			height : 14,
     			alt : 'Fermer le pop up',
     			title : 'Fermer le pop up',
     			styles : {
     				'margin-left' : '2%',
     				'float' : 'right',
     				'vertical-align': 'middle',
     				'cursor' :'pointer'
     			}
     		});
     	},
     	
     	setSizer : function() {
     		this.sizer = new Element('img', {
     			id : 'reduce',
     			src : 'pub/img/popreduce.gif',
     			width : 16,
     			height : 14,
     			alt : 'Réduire le pop up',
     			title : 'Réduire le pop up',
     			styles : {
     				'margin-left' : '2%',
     				'float' : 'right',
     				'vertical-align': 'middle',
     				'cursor' :'pointer'
     			}
     		});
     	},
     	
     	setTitle : function(title){
     		this.setSizer();
     		this.setCloser();
     		this.title = new Element('h3', {
     			id : 'up-title',
     			html : title,
     			styles : {
     				'background': '#000 url("pub/img/fond.gif") repeat-x top left',
     			 	'text-align': 'center',
     				margin : '0',
     			 	'margin-top' : '-2px',
     			 	padding : '0.5%',
     			 	color : 'white',		 	
     			}
     		});
     		this.container.adopt(this.title.adopt(this.closer, this.sizer));
     	},
     	
     	setLabel : function(label){
     		return new Element('label',{
     			html : label
     		});
     	},	
     	
     	setCompactBox : function(){
     		return new Element('div', {
     			styles : {
     				display: 'block',
    	 			clear : 'both',
    	 			width : '98%',
    	 			float :'left',
    	 			margin: 'auto',
    	 			'text-align': 'center',
    	 			padding : '1%',
    	 			'padding-top': '0'
     			}
     		});
     	},
     	
     	setBox : function(){
     		return new Element('div', {
     			styles : {
     				padding : '1%',
    	 			'margin-left': '5%',
    	 			'text-align': 'center',
    	 			display: 'block',
    	 			clear : 'none',
    	 			float :'left'
     			}
     		});
     	},
     	
     	_setDirBox : function(dirs){
     		var box = {};
     		var span = {};
     		var compact = this.setCompactBox().setStyles({
     			'background-color': 'white',
     			'color' : 'black'
     		});
     		dirs.each(function(dir, i){	
     			box[i] = this.setBox(); 			
     			var name = dir.substring(0, 1).toUpperCase()+ dir.substr(1);
     			var img = new Element('img',{
     				id : dir+'-'+i,
     				src : 'pub/img/dir-blue.png',
     				alt : name,
     				styles : { cursor : 'pointer'}
     			});
     			span[i] = new Element('span',{ html : name});
     			compact.adopt(box[i].adopt(img, new Element('br'), span[i]));
     			img.addEvent('click', function(){
     				this.screen.set('value', dir);
     				ids  = img.get('id').split('-');
     				if(ids[1] == i){
     					span[i].setStyle('color', 'red');
     				}
    				for(var j = 0; j < dirs.length; j++){
    					if(i !== j){
    						span[j].setStyle('color', 'black');
    					}
    				}	 				
     			}.bind(this));
     		}, this);
     		compact.inject(this.formUpload);
     	},
     	
     	_setWindowPopUp : function(){
     		this.container.setStyles({	
     			width : '340px',
     			height : 'auto',
     			border : '5px solid black',
     			position : 'absolute',
     			left : 0,
     			top  : 0 ,
     			'background-color': 'white',
    			'z-index' : 9999999,
    			color : 'black',
    			'font-weight' : 'bold',
    			cursor : 'move'	 			
     		}).adopt(this.formUpload);
     	},
     	
     	_buildForm : function(){
     		var compact = this.setCompactBox();
     		this.input = new Element('input', {
     			type : 'file',
     			name : 'userImage',
     			styles :{
     				'margin-top': '5%'
     			}
     		});
     		var inLabel = this.setLabel('Votre image : ');
     		var p = new Element('p');
     		p.adopt(inLabel, new Element('br'), this.input).inject(compact);
     		var p = new Element('p');
     		this.submit = new Element('input',{
     			type : 'submit',
     			value : 'Envoyer votre image'
     		});
     		p.adopt(this.screen, this.submit).inject(compact);
     		compact.inject(this.formUpload) 		
     	},
     	
     	movePosition : function(){	 	 		
     		var x = this.container.retrieve('xpos');
     		var ypos = this.container.retrieve('ypos');
     		var y = window.getScroll().y;
     		this.container.morph({
     			top : [ypos, y],
     			left : [ x, window.getSize().x.toInt() - this.container.getSize().x.toInt()]
     		});
     	},
     	
     	restorePosition : function() {	 		
     		var xpos = this.container.retrieve('xpos');
     		var ypos = this.container.retrieve('ypos');
     		this.container.morph({
     			top : ypos,
     			left : xpos
     		});
     	},
     	
     	run : function() {
     		this.button.addEvent('click', function(){
     			this.container.fade('in');
     			this.isOpen = true;	 			
     		}.bind(this));
     		this.closer.addEvent('click', function(){
     			this.container.fade('out');
     			this.isOpen = false;
     		}.bind(this));
     		this.sizer.addEvent('click', function(){
     			this.isResize = !this.isResize;
     			if(this.isResize){
     				this.sizer.set('src', 'pub/img/popreduce.gif');
     				this.restorePosition();
     				this.formUpload.slide('in');	
     			} else {
     				this.container.store('xpos', this.container.getPosition().x.toInt());
    		 		this.container.store('ypos', this.container.getPosition().y.toInt());
     				this.sizer.set('src', 'pub/img/poprestore.gif');
     				this.movePosition();
     				this.formUpload.slide('out');
     			} 			 			
     		}.bind(this));
     		window.addEvent('mousewheel', function(){
     			if(this.isOpen){			
    	 			this.container.morph({
    		 			top : window.getScroll().y
    		 		});
     			}
     		}.bind(this));
    	 }
    });
    


    le html pour tester l'uploader je ne vous mets pas les images donc le rendu risque d'en prendre un coup mais l'essentiel c'est le fonctionnement
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="pub/js/mootools-3.js"></script>
    <script type="text/javascript" src="pub/js/zcode/uploader.js"></script>
    <script type="text/javascript">
    
    window.addEvent('domready', function() {
    	var u = new IndyPopUploader();
    	u.run();
    });
    
    </script>
    <title>Maquette Indy - musics V3.0</title>
    
    </head>
    <body>	
    <h1>Test pop up</h1>
    <h2 id="testing"></h2>
    <div id="main">
    	<div id="indyloader">
    	</div>	
    	<textarea></textarea>
    	<a href="#" id="sending">uplaod</a>
    	<div id="button"></div>
    </div>
    </body>
    </html>
    

    fichier php

    <?php
    $name = $_FILES['userImage']['name'];
    $tmp = $_FILES['userImage']['tmp_name'];
    if(is_uploaded_file($tmp))
    {
    	if(is_dir('../tmp/')){
    		move_uploaded_file($tmp , '../tmp/'.$name);		
    		echo 'votre image est uploader';
    	} else {
    		echo 'dossier introuvable';
    	}
    }
    else
    {
    	echo 'un problème est survenu';
    }
    


    Je sais que c'est possible avec XMLHttpRequest2, mais là j'essaie de passer par une iframe et une target ajouter dynamiquement via js, le but à terme c'est de faire une barre de progression mais je me demande si c'est possible comme ça :euh:
    Quelqu'un à une idée ou un avis sur la question?

    merci
    franckysolo
    • Partager sur Facebook
    • Partager sur Twitter

    Upload Fichier Ajax

    × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
    × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
    • Editeur
    • Markdown