Advertisement
d4rky

jQuery - file upload like in Tumblr

Jan 9th, 2012
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * jQuery insertAtCaret
  3.  * Allows inserting text where the caret is in a textarea
  4.  * Copyright (c) 2003-2010 phpMyAdmin devel team
  5.  * Version: 1.0
  6.  * Developed by the phpMyAdmin devel team. Modified by Alex King and variaas
  7.  * http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript
  8.  * http://www.mail-archive.com/jquery-en@googlegroups.com/msg08708.html
  9.  * Licensed under the GPL license:
  10.  * http://www.gnu.org/licenses/gpl.html
  11.  */
  12. (function(a){a.fn.insertAtCaret=function(b){return this.each(function(){if(document.selection){this.focus();sel=document.selection.createRange();sel.text=b;this.focus();}else{if(this.selectionStart||this.selectionStart=="0"){var d=this.selectionStart;var c=this.selectionEnd;var e=this.scrollTop;this.value=this.value.substring(0,d)+b+this.value.substring(c,this.value.length);this.focus();this.selectionStart=d+b.length;this.selectionEnd=d+b.length;this.scrollTop=e;}else{this.value+=b;this.focus();}}});};})(jQuery);
  13.  
  14. /* ------------------ */
  15.  
  16. http://valums.com/ajax-upload/
  17.  
  18. /* ------------------ */
  19.  
  20. // dodawanie, _UPLOAD_ACTION i _UPLOAD_DIR, żeby działało przy url rewrite gdy przeniosę z dev na produkcję
  21. // skrypt zwraca JSONem listę plików przez json_encode(array('files' => array('nazwapliku', 'nazwapliku', 'nazwapliku'))), żeby dało się dodać w razie czego multiupload plików i tylko zmodyfikować JS ;)
  22.  
  23.     $("textarea.addUpload").each(function()
  24.     {
  25.         var e = $(this);
  26.         e.before("<div class='upload_button' id='upload_" + e.attr('name') + "'>Dodaj zdjęcie</div>");
  27.         new AjaxUpload('upload_' + e.attr('name'),
  28.         {
  29.             action: _UPLOAD_ACTION,
  30.             name: 'filename',
  31.             responseType: 'json',
  32.             onComplete: function(file, response)
  33.             {
  34.                 if(typeof response.error != "undefined")
  35.                 {
  36.                     alert("Wystąpił błąd podczas dodawania pliku.");
  37.                 }
  38.                 else
  39.                 {
  40.                     var textarea = $("textarea[name='" + this._button.id.replace(/^upload_/,'') + "']");
  41.                     for(i=0, l=response.files.length; i < l; i++)
  42.                     {
  43.                         textarea.insertAtCaret('<img src="' + _UPLOAD_DIR + "/" + response.files[i] + '">');                       
  44.                     }
  45.                 }  
  46.             }
  47.         });
  48.     });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement