app.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var size = 0;
  2. $("#upload").click(upload);
  3. // 绑定所有type=file的元素的onchange事件的处理函数
  4. $(':file').change(function() {
  5. var file = this.value;
  6. if (file) {
  7. name = file.name;
  8. size = file.size;
  9. type = file.type;
  10. // url = window.URL.createObjectURL(file);
  11. }
  12. });
  13. /**
  14. * 上传文件
  15. */
  16. function upload() {
  17. $('#result').html("");
  18. var value = document.getElementById("file").value;
  19. if (!value) {
  20. $('#progressDiv').css("display", "hidden");
  21. $("#result").html("文件为空,无法进行上传!");
  22. return;
  23. }
  24. // 创建FormData对象,初始化为form表单中的数据
  25. var formData = new FormData($('form')[0]);
  26. // 显示进度
  27. $('#progressDiv').css("display", "block");
  28. // $('#progressDiv').toggle();
  29. // ajax异步上传
  30. $.ajax({
  31. url : "upload",
  32. type : "POST",
  33. data : formData,
  34. xhr : function() {
  35. myXhr = $.ajaxSettings.xhr();
  36. if (myXhr.upload) {
  37. // 绑定progress事件的回调函数
  38. myXhr.upload.addEventListener('progress',
  39. progressHandlingFunction, false);
  40. }
  41. return myXhr;
  42. },
  43. success : function(result) {
  44. $("#result").html(result);
  45. },
  46. contentType : false,
  47. processData : false
  48. });
  49. }
  50. // 上传进度回调函数:
  51. function progressHandlingFunction(e) {
  52. if (e.lengthComputable) {
  53. $('progress').attr({
  54. value : e.loaded,
  55. max : e.total
  56. }); // 更新数据到进度条
  57. var percent = e.loaded / e.total * 100;
  58. $('#progress').html(
  59. e.loaded + "/" + e.total + " bytes. " + percent.toFixed(2)
  60. + "%");
  61. }
  62. }