upload.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. ;(function(){
  2. function upload(cb, opt){
  3. var el = $(this); cb = cb || function(){}; opt = opt || {};
  4. el.on('drop', function(e){
  5. e.preventDefault();
  6. upload.drop(((e.originalEvent||{}).dataTransfer||{}).files, 0);
  7. }).on('dragover', function(e){
  8. e.preventDefault();
  9. });
  10. upload.drop = function(files,i){
  11. if(opt.max && (files[i].fileSize > opt.max || files[i].size > opt.max)){
  12. cb({err: "File size is too large.", file: file[i]}, upload);
  13. if(files[++i]){ upload.drop(files,i) }
  14. return false;
  15. }
  16. reader = new FileReader();
  17. reader.onload = function(e){
  18. cb({file: files[i], event: e, id: i}, upload);
  19. if(files[++i]){ upload.drop(files,i) }
  20. };
  21. if(files[i]){ reader.readAsDataURL(files[i]) }
  22. }
  23. }
  24. upload.shrink = function(e, cb, w, h){ // via stackoverflow
  25. if(!e){ return cb && cb({err: "No file!"}) }
  26. if(e.err){ return }
  27. var file = (((e.event || e).target || e).result || e), img = new Image();
  28. img.crossOrigin = "Anonymous";
  29. img.src = file;
  30. img.onload = function(){
  31. if(img.width < (w = w || 1000) && img.height < (h||Infinity) && "data:" == file.slice(0,5)){
  32. e.base64 = file;
  33. return cb(e || file);
  34. }
  35. if(!h){ h = img.height * (w / img.width) }
  36. var canvas = document.createElement('canvas'), ctx = canvas.getContext('2d');
  37. canvas.width = w;
  38. canvas.height = h;
  39. ctx.drawImage(img, 0, 0, w, h); // draw source image to canvas.
  40. var b64 = e.base64 = canvas.toDataURL(); // base64 the compressed image.
  41. cb((e.base64 && e) || b64);
  42. };
  43. }
  44. $.fn.upload = upload;
  45. }());