* jQuery ajax FormData 上传文件 template
$.ajax({ url: url, type: 'POST', data: new FormData(form), dataType: 'json', cache: false, processData: false, contentType: false, }).done(function(data) { myalert.success("视频文件上传成功", true); // 提示信息不消失 console.log(data); return false; }).fail(function(jqXHR, textStatus, errorThrown) { });
关键的3个选项:
cache: false,
processData: false,
contentType: false,
* demo:
<html> <head> <meta charset="UTF-8"> <title>上传校长寄语视频</title> <link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css"> <style> #wrapper { 500px; } .form-control { margin-bottom: 20px; } .btn-primary { margin-left: 70px; 170px; } iframe { 0; height: 0; border: 0; } .invisible { display: none; } #alert { position: fixed; top: 20px; right: 20px; z-index: 2; } #wrapper ul { margin: 20px 0; } li { list-style: none; } .ui-widget-header { border: 1px solid #ACD978; background: #A1D16B; } #progressbar { border: none; } </style> </head> <body> <div class="container" id="wrapper"> <form method="POST" enctype="multipart/form-data"> <div class="form-group"> <label for="schoolName">学校名称:</label> <input class="form-control" id="schoolName" type="text" name="schoolName" /> </div> <div class="form-group"> <label for="file">选择文件:</label> <input id="file" class="form-control" type="file" name="file" /> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">上传</button> </div> </form> <div id="progressbar"></div> <ul> <li id="fileName"></li> <li id="fileSize"></li> <li id="fileType"></li> <li id="progressNumber"></li> </ul> </div> <iframe id="J_iframe" name="demoIframe" class="invisible"></iframe> <!-- TODO: 播放预览 --> <video class="invisible" width="320" height="240" src="http://47.92.133.100:8089/dd.mp4" controls="controls"></video> <script type="text/javascript" src="../assets/ckeditor/js/require.js"></script> <script type="text/javascript" src="./js/config.js"></script> <script> var form = document.forms[0]; form.action = window.CONTEXT_PATH + "/school/uploadMasterVideo"; // form.target = "demoIframe"; require(['jquery', 'alert', 'jquery-ui'], function($, m) { $("#file").on("change", function() { var file = this; var fileSize = 0; if (file.size > 1024 * 1024) { fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'; } else { fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'; } var index = file.value.lastIndexOf("/") if (index < 0) { index = file.value.lastIndexOf("\"); } var filename = file.value.substring(index + 1); document.getElementById('fileName').innerHTML = '文件名: ' + filename; document.getElementById('fileSize').innerHTML = '文件大小: ' + fileSize; document.getElementById('fileType').innerHTML = '文件类型: ' + file.type; console.log(file.size); }); var myalert = m.alert.getInstance(); var $progressbar = $("#progressbar").show(); form.onsubmit = function(e) { e.preventDefault(); var url = this.action, fd = new FormData(form); /* $.ajax({ url: url, type: 'POST', data: new FormData(form), dataType: 'json', cache: false, processData: false, contentType: false, }).done(function(data) { myalert.success("视频文件上传成功", true); // 提示信息不消失 console.log(data); return false; }).fail(function(jqXHR, textStatus, errorThrown) { }); */ // 进度百分比 var p = document.getElementById('progressNumber'); var xhr = new XMLHttpRequest(); if (!xhr) { document.write("<h1>当前浏览器不支持上传文件</h1>"); return false; } xhr.upload.addEventListener("progress", function(evt) { var text, s = "进度: ", percentComplete; if (evt.lengthComputable) { percentComplete = Math.round(evt.loaded * 100 / evt.total); s += percentComplete.toString() + '%'; $progressbar.progressbar("value", percentComplete); } else { s += '无法计算'; } text = document.createTextNode(s); p.innerHTML = ""; p.append(text); if (percentComplete === 100) { myalert.info("视频处理中..."); } }, false); xhr.addEventListener("load", function(evt) { /* 当服务器响应后,这个事件就会被触发 */ var txt = evt.target.responseText; console.log(txt); var resp = JSON.parse(txt); if (resp.status === 200) { myalert.success("视频文件上传成功", true); } else { myalert.fail(resp.msg, resp.error); } }, false); xhr.addEventListener("error", function() { myalert.fail("上传文件发生了错误尝试"); }, false); xhr.addEventListener("abort", function() { myalert.fail("上传被用户取消或者浏览器断开连接"); }, false); xhr.open("POST", url); xhr.send(fd); myalert.info("视频文件上传中..."); }; }); require(['jquery', 'jquery-cookie'], function($) { $("#schoolName").val($.cookie("schoolName")); // iframe上传文件 cross domain x $("#J_iframe").on("load", function() { var s = this.contentDocument.body.textContent; var resp = JSON.parse(s) || {}; console.log(resp); }); }); require(['jquery', 'jquery-ui'], function($) { css("../assets/jqui/jquery-ui.css"); var schoolNames = []; $.ajax({ type: 'GET', url: window.CONTEXT_PATH + '/system/school/archive', }).done(function(data) { // for autocomplete, school name list data.entity.forEach(function(ent) { schoolNames.push(ent.name); }); }); $("#progressbar").progressbar({ value: 0 }); $("#schoolName").autocomplete({ source: schoolNames, autoFocus: true }); }); </script> </body> </html>
alert.js
(function() { var m = function(timeout) { this.timeout = timeout ? timeout : 3000; var a = document.createElement("div"); a.id = "alert"; a.className = "alert alert-danger"; a.innerHTML = "An error occurred during submitting..."; a.style.display = 'none'; document.body.append(a); this.$alert = a; }; m.getInstance = function() { if (!this.$alert) { this.$alert = new m(); } return this.$alert; }; m.prototype.success = function(msg, b) { var self = this; self.$alert.className = "alert alert-success"; self.$alert.innerHTML = msg; self.$alert.style.display = 'inline-block'; if (typeof b !== "undefined" && b) { } else { setTimeout(function() { self.$alert.style.display = "none"; }, self.timeout); } }; m.prototype.fail = function(msg) { var self = this; self.$alert.className = "alert alert-danger"; self.$alert.innerHTML = msg; self.$alert.style.display = 'inline-block'; setTimeout(function() { self.$alert.style.display = "none"; }, self.timeout); }; m.prototype.info = function(msg) { var self = this; self.$alert.className = "alert alert-info"; self.$alert.innerHTML = msg; self.$alert.style.display = 'inline-block'; }; define({ alert: m }); })();
config.js
// require.js 依赖的js库路径配置 require.config({ paths : { // "jquery-1.12" : "../assets/jqui/external/jquery/jquery", "jquery-ui": "../assets/jqui/jquery-ui", // "jquery": "../assets/bootstrap/js/jquery-3.3.1.min", "jquery": "../assets/ckeditor/js/jquery-3.2.1", "ckeditor-core": "../assets/ckeditor/ckeditor", 'ckeditor-jquery': "../assets/ckeditor/adapters/jquery", "jquery-cookie": "../assets/js/jquery.cookie", "bootstrap": "../assets/bootstrap/js/bootstrap", "alert": "js/lib/alert", "supersized": "../assets/js/login/supersized.3.2.7", "url-param": "js/util/getUrlParam", 'image-preview': 'js/util/preview' }, shim: { 'ckeditor-jquery':{ deps:['jquery','ckeditor-core'] }, 'jquery-cookie': { deps: ['jquery'] }, 'bootstrap': { deps: ['jquery'] }, 'jquery-ui':{ deps: ['jquery'] } } }); // 后台ajax url前缀 var CONTEXT_PATH = "http://192.168.10.137:9999"; // var CONTEXT_PATH = "http://zhanghum:9999";