JS实现伪Ajax上传文件

合集下载

通过Ajax上传文件

通过Ajax上传文件

var parameters = "fileSize=" + encodeURI(this.fileSize) +
"&fileName=" + encodeURI(this.fileName)+
"&overwriteFile=" + encodeURI(document.getElementById("overwriteFile").checked);
{
if (fileName == null || fileName == string.Empty || file == null)
然后通过ajax的open方法和send方法提交到服务,我觉得这种方法有些局限性(现在毕竟使用firefox的用户还是不太多),不过在firefox下能够显示已经不错了;
后来通过在上找到通过使用ms系统中控件的方法来实现的方式,我把列出来以后说不定会用上哦;
xmlhttp.open("POST","<A href="http://localhost/AJAXUpload/Upload.asmx/InitUpload">http://localhost/AJAXUpload/Upload.asmx/InitUpload<;/A>", true);
xmlhttp.send(xmlSOAP);
}
通过使用ADODB.Stream控件来实现文件的读取,将文件内容封装到了xml文件将xml文件上传到服务器端
以下是服务器端的代码:
[WebMethod]
public XmlDocument InitUpload(int fileSize, string fileName, bool overwriteFile )

通过Ajax方式上传文件,使用FormData进行Ajax请求

通过Ajax方式上传文件,使用FormData进行Ajax请求

通过Ajax⽅式上传⽂件,使⽤FormData进⾏Ajax请求通过传统的form表单提交的⽅式上传⽂件:[html]1. <form id= "uploadForm" action= "http://localhost:8080/cfJAX_RS/rest/file/upload" method= "post" enctype ="multipart/form-data">2. <h1 >测试通过Rest接⼝上传⽂件 </h1>3. <p >指定⽂件名: <input type ="text" name="filename" /></p>4. <p >上传⽂件: <input type ="file" name="file" /></p>5. <p >关键字1: <input type ="text" name="keyword" /></p>6. <p >关键字2: <input type ="text" name="keyword" /></p>7. <p >关键字3: <input type ="text" name="keyword" /></p>8. <input type ="submit" value="上传"/>9. </form>不过传统的form表单提交会导致页⾯刷新,但是在有些情况下,我们不希望页⾯被刷新,这种时候我们都是使⽤Ajax的⽅式进⾏请求的。

jquery实现异步文件上传ajaxfileupload.js

jquery实现异步文件上传ajaxfileupload.js

jquery实现异步⽂件上传ajaxfileupload.js 本⽂实例为⼤家分享了jquery实现异步⽂件上传的具体代码,供⼤家参考,具体内容如下ajaxfileupload.js 异步上传⽂件:直接引⽤。

调⽤⽅法:$.ajaxFileUpload({url:'',//后台接⼝地址type: "post",secureuri: false, //⼀般设置为falsefileElementId: 'ofx', // 上传⽂件的id、name属性名dataType: 'json',success: function(data, status){},error: function(data, status, e){}});下⾯是ajaxfileupload.js,可直接复制并引⽤。

jQuery.extend({createUploadIframe: function(id, uri){//create framevar frameId = 'jUploadFrame' + id;var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';if(window.ActiveXObject){if(typeof uri== 'boolean'){iframeHtml += ' src="' + 'javascript:false' + '"';}else if(typeof uri== 'string'){iframeHtml += ' src="' + uri + '"';}}iframeHtml += ' />';jQuery(iframeHtml).appendTo(document.body);return jQuery('#' + frameId).get(0);},createUploadForm: function(id,fileElementId,data,fileElement){//create formvar formId = 'jUploadForm' + id;var fileId = 'jUploadFile' + id;var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); if(data){for(var i in data){jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);}}if(typeof(fileElementId) == 'string'){fileElementId = [fileElementId];}for(var i in fileElementId){var oldElement = jQuery('#' + fileElementId[i]);var newElement = jQuery(oldElement).clone();jQuery(oldElement).attr('id', fileId);jQuery(oldElement).before(newElement);jQuery(oldElement).appendTo(form);}//set attributesjQuery(form).css('position', 'absolute');jQuery(form).css('top', '-1200px');jQuery(form).css('left', '-1200px');jQuery(form).appendTo('body');return form;},ajaxFileUpload: function(s) {// TODO introduce global settings, allowing the client to modify them for all requests, not only timeouts = jQuery.extend({}, jQuery.ajaxSettings, s);var id = new Date().getTime()var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data),s.fileElement);var io = jQuery.createUploadIframe(id, s.secureuri);var frameId = 'jUploadFrame' + id;var formId = 'jUploadForm' + id;// Watch for a new set of requestsif ( s.global && ! jQuery.active++ ){jQuery.event.trigger( "ajaxStart" );}var requestDone = false;// Create the request objectvar xml = {}if ( s.global )jQuery.event.trigger("ajaxSend", [xml, s]);// Wait for a response to come backvar uploadCallback = function(isTimeout){var io = document.getElementById(frameId);try{if(io.contentWindow){xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;}else if(io.contentDocument){xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document; }}catch(e){jQuery.handleError(s, xml, null, e);}if ( xml || isTimeout == "timeout"){requestDone = true;var status;try {status = isTimeout != "timeout" ? "success" : "error";// Make sure that the request was successful or notmodifiedif ( status != "error" ){// process the data (runs the xml through httpData regardless of callback)var data = jQuery.uploadHttpData( xml, s.dataType );// If a local callback was specified, fire it and pass it the dataif ( s.success )s.success( data, status );// Fire the global callbackif( s.global )jQuery.event.trigger( "ajaxSuccess", [xml, s] );} elsejQuery.handleError(s, xml, status);} catch(e){status = "error";jQuery.handleError(s, xml, status, e);}// The request was completedif( s.global )jQuery.event.trigger( "ajaxComplete", [xml, s] );// Handle the global AJAX counterif ( s.global && ! --jQuery.active )jQuery.event.trigger( "ajaxStop" );// Process resultif ( plete )plete(xml, status);jQuery(io).unbind()setTimeout(function(){ try{jQuery(io).remove();jQuery(form).remove();} catch(e){jQuery.handleError(s, xml, null, e);}}, 100)xml = null}}// Timeout checkerif ( s.timeout > 0 ){setTimeout(function(){// Check to see if the request is still happeningif( !requestDone ) uploadCallback( "timeout" );}, s.timeout);}try{var form = jQuery('#' + formId);jQuery(form).attr('action', s.url);jQuery(form).attr('method', 'POST');jQuery(form).attr('target', frameId);if(form.encoding){jQuery(form).attr('encoding', 'multipart/form-data');}else{jQuery(form).attr('enctype', 'multipart/form-data');}jQuery(form).submit();} catch(e){jQuery.handleError(s, xml, null, e);}jQuery('#' + frameId).load(uploadCallback);return {abort: function(){try{jQuery('#' + frameId).remove();jQuery(form).remove();}catch(e){}}};},uploadHttpData: function( r, type ) {var data = !type;data = type == "xml" || data ? r.responseXML : r.responseText; // If the type is "script", eval it in global contextif ( type == "script" )jQuery.globalEval( data );// Get the JavaScript object, if JSON is used.if ( type == "json" ){以下为新增代码///data = r.responseText;var start = data.indexOf(">");if(start != -1) {var end = data.indexOf("<", start + 1);if(end != -1) {data = data.substring(start + 1, end);}}}///以上为新增代码///eval( "data = " + data );// evaluate scripts within htmlif ( type == "html" )jQuery("<div>").html(data).evalScripts();return data;},handleError: function( s, xml, status, e ) {// If a local callback was specified, fire itif ( s.error )s.error( xml, status, e );// Fire the global callbackif ( s.global )jQuery.event.trigger( "ajaxError", [xml, s, e] );}});更多精彩内容,请点击,进⾏深⼊学习和研究。

ajaxfileupload.js实现上传文件功能

ajaxfileupload.js实现上传文件功能

ajaxfileupload.js实现上传⽂件功能使⽤ajaxfileupload.js实现上传⽂件功能⼀、ajaxFileUpload是⼀个异步上传⽂件的jQuery插语法:$.ajaxFileUpload([options])options参数说明:1、url 上传处理程序地址2、fileElementId ⽂件选择框的id属性,即的id3、secureuri 是否启⽤安全提交,默认为false4、dataType 服务器返回的数据类型。

可以为xml,script,json,html。

如果不填写,jQuery会⾃动判断5、success 服务器响应成功后的处理函数,参数data就是服务器返回的数据6、error 服务器响应失败后的处理函数7、data ⾃定义参数,当有数据要和上传的⽂件⼀起传到后台处理的时候会⽤到。

这⾥注意,数据格式⽐较严格{param:[{‘param1':'value1','param2':'value2' },{‘param1':'value3','param2':'value4' }]}, 其中单引号不能改为双引号8、type 提交数据的⽅式,⼀般为post⼆、使⽤⽅法第⼀步、先引⼊jquery和ajaxFileUpload插件,注意先后顺序:<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script><script type= "text/javascript" src= "js/ajaxfileupload.js" ></script>第⼆步、html代码原始的,控件展⽰效果如下:因为原始控件的样式⽆法改变,所以我们⼀般会让这个标签隐藏,然后点击别的标签来触发上传控件。

$.ajaxfileupload用法

$.ajaxfileupload用法

$.ajaxfileupload用法在Web开发中,文件上传是一种常见的操作,而使用Ajax技术可以实现异步文件上传,提高页面性能和用户体验。

jQuery中的$.ajaxFileUpload方法提供了一种简单易用的方式来实现文件上传功能。

$.ajaxFileUpload方法用于通过Ajax方式上传文件,支持多文件上传和回调函数的使用。

它接受三个参数:文件路径、回调函数和可选配置参数。

通过该方法,可以实现文件上传的异步操作,避免了页面刷新带来的影响,提高了页面性能。

二、用法示例```javascript//创建一个用于上传文件的表单元素varform=$('<form/>',{'method':'POST','enctype':'multipart/form-data'}).appendTo('body');//添加文件输入框varinput=$('<input/>',{'type':'file','name':'file','value':''}).appendTo(form);//触发文件选择器,选择文件input.trigger('click');//添加文件到表单中input.on('change',function(){varfiles=input.prop('files');if(files&&files.length>0){//创建AjaxFileUpload对象varupload=newAjaxFileUpload(form,{//配置选项action:'/upload',//上传接口地址autoSubmit:false,//不自动提交表单responseType:'json',//返回数据类型为JSONfileVal:'file',//文件字段名onComplete:function(data){//上传完成后回调函数console.log(data);//打印返回数据//TODO:处理上传结果,更新页面等操作},onError:function(error){//上传过程中出现错误时回调函数console.log(error);//打印错误信息//TODO:处理上传错误,显示错误提示等操作}});//开始上传文件upload.upload();}else{console.log('请选择文件');//输出提示信息}});```在上述示例中,首先创建了一个表单元素和一个文件输入框,并设置了表单的enctype属性为multipart/form-data,用于多文件上传。

如何在JavaScript中发送 AJAX 请求

如何在JavaScript中发送 AJAX 请求

如何在JavaScript中发送 AJAX 请求在JavaScript中发送AJAX请求可以通过XMLHttpRequest对象或者fetch函数来实现。

AJAX(Asynchronous JavaScript and XML)是一种在不重新加载整个页面的情况下,通过发送异步请求与服务器进行通信的技术。

1.使用XMLHttpRequest发送AJAX请求:首先,我们需要创建一个XMLHttpRequest对象,可以通过new关键字实例化它:```javascriptvar xhr = new XMLHttpRequest();```使用open方法配置请求的类型(GET、POST等)和URL:```javascriptxhr.open(method, url, async);```- method:请求的类型,可以是GET或POST。

- url:服务器的URL地址。

- async:是否异步发送请求,默认为true(异步)。

添加一个监听器,当请求的状态发生变化时触发:```javascriptxhr.onreadystatechange = function() {if(xhr.readyState === 4 && xhr.status === 200) { //请求成功处理} else {//请求失败处理}};```readyState属性表示请求的当前状态,status属性表示服务器返回的状态码。

设置请求头信息:```javascriptxhr.setRequestHeader(header, value);```- header:要设置的请求头字段。

- value:请求头字段的值。

发送请求:```javascriptxhr.send(data);```- data:需要发送给服务器的数据,仅在POST请求时使用。

这样就可以在发送请求后获取到服务器返回的数据,可以通过xhr.responseText或者xhr.responseXML来获取。

使用ajaxfileupload.js实现ajax上传文件php版

使用ajaxfileupload.js实现ajax上传文件php版

使⽤ajaxfileupload.js实现ajax上传⽂件php版⽆论是PHP,还是其他的服务端脚本都提供了⽂件上传功能,实现起来也⽐较简单。

⽽利⽤JavaScript来配合,即可实现Ajax⽅式的⽂件上传。

虽然jQuery本⾝没有提供这样的简化函数,但有不少插件可以实现。

其中,提供的ajaxfileupload.js是⼀个轻量的插件,⽽且编写⽅式与jQuery提供的全局⽅法$.post()⾮常相似,简单易⽤。

不过,该插件实在太简化了,除了可提供需上传⽂件的路径外,也就不能传递额外的值到后台服务端。

所以,我修改了⼀下该脚本,增加个⼀个data对象参数。

⼀、原理我这⾥使⽤的是PHP作为服务端脚本,⼏乎在每本较少PHP的书上都会提到如何使⽤move_uploaded_file()⽅法来上传⽂件,这⾥我就不再细说了。

我想说的是,利⽤Ajax上传的原理。

因为⼀直在使⽤jQuery库,所以当想到Ajax时,第⼀反应就是试试$.post()⽅法,利⽤各选择器得到file⽂件框中的value值,然后提交到后台服务端。

当然,后来证明这是不⾏的。

(正因为这问题,我还查了不少资料,⽹上还提供了不少ASP等⽅式的脚本,真不知道该说什么好。

)回到正题,要实现Ajax⽅式上传,其实并不难,⽅法也有不少。

⽽本⽂提到的的ajaxfileupload.js插件就是使⽤iframe的⽅式。

这也是在不使⽤JavaScript脚本时,要实现不刷新页⾯上传时常见的⽅法。

(本博客bo-blog后台撰写⽇志就是⽤该⽅法)⽽ajaxfileupload.js插件也很简单,就是先利⽤jQuery的选择器获得file⽂件上传框中的⽂件路径值,然后动态的创建⼀个iframe,并在⾥⾯建⽴⼀个新的file ⽂件框,提供post⽅式提交到后台。

最后,返回结果到前台。

⼆、使⽤ajaxfileupload.js插件的使⽤很简单。

前台HTML代码类似:<script type="text/javascript">$(#buttonUplod).click(function () {$.ajaxFileUpload ({url:'doajaxfileupload.php', //你处理上传⽂件的服务端secureuri:false, //与页⾯处理代码中file相对应的ID值fileElementId:'img',dataType: 'json', //返回数据类型:text,xml,json,html,scritp,jsonp五种success: function (data) {alert(data.file_infor);}})});</script><input id="img" type="file" size="45" name="img" ><button id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button>后台doajaxfileupload.php脚本:<?php$upFilePath = "../attachment/";$ok=@move_uploaded_file($_FILES['img']['tmp_name'],$upFilePath);if($ok === FALSE){echo json_encode('file_infor'=>'上传失败');}else{echo json_encode('file_infor'=>'上传成功');}>为了测试,可以使⽤类似下⾯的⽅式保存传递过来的变量值:$file_info = var_export($_FILES,true);$ok = file_put_contents("../attachment/file_info.txt",$file_info);if ($ok) exit(json_encode('file_infor'=>'上传成功'));exit (json_encode('file_infor'=>'上传失败'));※注意请留意HTML代码⽂件框中的标记:1. id='img'是⽤于给ajaxfileupload.js插件的fileElementId:'img'识别的,jQuery选择器会利⽤该字符串获得⽂本框的值;2. name='img'是⽤于通过post⽅式提交到后台脚本时,PHP通过$_FILES['img']读取上传⽂件的数据,若没有该值,$_FILES 变量为空;所以,这两个值缺⼀不可,也不可混淆。

使用Ajaxuploadjs上传文件

使用Ajaxuploadjs上传文件

使用Ajaxupload.js上传文件大岩不灿发表于2014年1月12日浏览2,164 次ajaxupload.js 是一款使用jquery上传文件的js插件,对于简单的文件上传,足够可以应付。

该插件主要有以下几个选项:1 2 3 4 5 6 7 8 9101112131415 settings ={action:'upload.php',//要提交的地址name:'userfile',//参数名次data:{},//和文件一起提交的其它参数autoSubmit:true,//选中文件后是否就提交responseType:false,//返回的相应格式,如果是text格式的,会在响应前后加上一个<pre></pre>标签hoverClass:'hover',disabledClass:'disabled',onChange:function(file, extension){//在选中了文件的时候触发},onSubmit:function(file, extension){//在提交的时候触发},onComplete:function(file, response){//上传结束的时候触发}}你可以使用非自动提交的方式上传文件。

代码示例如下:1 2 3 4 5 6 7 8 91011121314151617 var ajaxupload =new AjaxUpload($("#uploadFile_button"),{ action:"upload.action",type:"POST",data:{},autoSubmit:false,responseType:"json",name:'file',onChange:function(file, ext){if(ext &&(/^(xls)$/.test(ext))){alert("只支持xls格式的文件");}},onComplete:function(file, resp){alert("上传成功");}});以上代码绑定了id=uploadFile_button的html元素,只要点击它,就会弹出选择文件的对话框。

AjaxUpLoad.js实现文件上传

AjaxUpLoad.js实现文件上传

AjaxUpLoad.js实现⽂件上传AjaxUpload.js⽂件的代码,供⼤家参考,具体内容如下/*** AJAX Upload ( /ajax-upload/ )* Copyright (c) Andris Valums* Licensed under the MIT license ( /mit-license/ )* Thanks to Gary Haran, David Mark, Corey Burns and others for contributions*/(function () {/* global window *//* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true */ /*** Wrapper for FireBug's console.log*/function log() {if (typeof(console) != 'undefined' && typeof(console.log) == 'function') {Array.prototype.unshift.call(arguments, '[Ajax Upload]');console.log(Array.prototype.join.call(arguments, ' '));}}/*** Attaches event to a dom element.* @param {Element} el* @param type event name* @param fn callback This refers to the passed element*/function addEvent(el, type, fn) {if (el.addEventListener) {el.addEventListener(type, fn, false);} else if (el.attachEvent) {el.attachEvent('on' + type, function () {fn.call(el);});} else {throw new Error('not supported or DOM not loaded');}}/*** Attaches resize event to a window, limiting* number of event fired. Fires only when encounteres* delay of 100 after series of events.** Some browsers fire event multiple times when resizing* /dom/events/resize.html** @param fn callback This refers to the passed element*/function addResizeEvent(fn) {var timeout;addEvent(window, 'resize', function () {if (timeout) {clearTimeout(timeout);}timeout = setTimeout(fn, 100);});}// Needs more testing, will be rewriten for next version// getOffset function copied from jQuery lib (/)if (document.documentElement.getBoundingClientRect) {// Get Offset using getBoundingClientRect// /blog/getboundingclientrect-is-awesome/var docElem = doc.documentElement; // for ievar clientTop = docElem.clientTop || body.clientTop || 0;var clientLeft = docElem.clientLeft || body.clientLeft || 0;// In Internet Explorer 7 getBoundingClientRect property is treated as physical,// while others are logical. Make all logical, like in IE8.var zoom = 1;if (body.getBoundingClientRect) {var bound = body.getBoundingClientRect();zoom = (bound.right - bound.left) / body.clientWidth;}if (zoom > 1) {clientTop = 0;clientLeft = 0;}var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;return {top: top,left: left};};} else {// Get offset adding all offsetsvar getOffset = function (el) {var top = 0,left = 0;do {top += el.offsetTop || 0;left += el.offsetLeft || 0;el = el.offsetParent;} while (el);return {left: left,top: top};};}/*** Returns left, top, right and bottom properties describing the border-box,* in pixels, with the top-left relative to the body* @param {Element} el* @return {Object} Contains left, top, right,bottom*/function getBox(el) {var left, right, top, bottom;var offset = getOffset(el);left = offset.left;top = offset.top;right = left + el.offsetWidth;bottom = top + el.offsetHeight;return {left: left,right: right,top: top,bottom: bottom};}/*** Helper that takes object literal* and add all properties to element.style* @param {Element} el* @param {Object} styles*/if (styles.hasOwnProperty(name)) {el.style[name] = styles[name];}}}/*** Function places an absolutely positioned* element on top of the specified element* copying position and dimentions.* @param {Element} from* @param {Element} to*/function copyLayout(from, to) {var box = getBox(from);addStyles(to, {position: 'absolute',left: box.left + 'px',top: box.top + 'px',width: from.offsetWidth + 'px',height: from.offsetHeight + 'px'});}/*** Creates and returns element from html chunk* Uses innerHTML to create an element*/var toElement = (function () {var div = document.createElement('div');return function (html) {div.innerHTML = html;var el = div.firstChild;return div.removeChild(el);};})();/*** Function generates unique id* @return unique id*/var getUID = (function () {var id = 0;return function () {return 'ValumsAjaxUpload' + id++;};})();/*** Get file name from path* @param {String} file path to file* @return filename*/function fileFromPath(file) {return file.replace(/.*(\/|\\)/, "");}/*** Get file extension lowercase* @param {String} file name* @return file extenstion*/function getExt(file) {return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : ''; }function hasClass(el, name) {var re = new RegExp('\\b' + name + '\\b');return re.test(el.className);if (!hasClass(el, name)) {el.className += ' ' + name;}}function removeClass(el, name) {var re = new RegExp('\\b' + name + '\\b');el.className = el.className.replace(re, '');}function removeNode(el) {el.parentNode.removeChild(el);}/*** Easy styling and uploading* @constructor* @param button An element you want convert to* upload button. Tested dimentions up to 500x500px* @param {Object} options See defaults below.*/window.AjaxUpload = function (button, options) {this._settings = {// Location of the server-side upload scriptaction: 'upload.php',// File upload namename: 'userfile',// Additional data to senddata: {},// Submit file as soon as it's selectedautoSubmit: true,// The type of data that you're expecting back from the server.// html and xml are detected automatically.// Only useful when you are using json data as a response.// Set to "json" in that case.responseType: false,// Class applied to button when mouse is hoveredhoverClass: 'hover',// Class applied to button when AU is disableddisabledClass: 'disabled',// When user selects a file, useful with autoSubmit disabled// You can return false to cancel uploadonChange: function (file, extension) {},// Callback to fire before file is uploaded// You can return false to cancel uploadonSubmit: function (file, extension) {},// Fired when file upload is completed// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!onComplete: function (file, response) {}};// Merge the users options with our defaultsfor (var i in options) {if (options.hasOwnProperty(i)) {this._settings[i] = options[i];}}// button isn't necessary a dom elementif (button.jquery) {// jQuery object was passedbutton = button[0];} else if (typeof button == "string") {if (/^#.*/.test(button)) {// If jQuery user passes #elementId don't break itbutton = button.slice(1);}button = document.getElementById(button);}if (!button || button.nodeType !== 1) {throw new Error("Please make sure that you're passing a valid element");// disable linkaddEvent(button, 'click', function (e) {if (e && e.preventDefault) {e.preventDefault();} else if (window.event) {window.event.returnValue = false;}});}// DOM elementthis._button = button;// DOM elementthis._input = null;// If disabled clicking on button won't do anythingthis._disabled = false;// if the button was disabled before refresh if will remain// disabled in FireFox, let's fix itthis.enable();this._rerouteClicks();};// assigning methods to our classAjaxUpload.prototype = {setData: function (data) {this._settings.data = data;},disable: function () {addClass(this._button, this._settings.disabledClass);this._disabled = true;var nodeName = this._button.nodeName.toUpperCase();if (nodeName == 'INPUT' || nodeName == 'BUTTON') {this._button.setAttribute('disabled', 'disabled');}// hide inputif (this._input) {// We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it// has display none when user selects a filethis._input.parentNode.style.visibility = 'hidden';}},enable: function () {removeClass(this._button, this._settings.disabledClass);this._button.removeAttribute('disabled');this._disabled = false;},/*** Creates invisible file input* that will hover above the button* <div><input type='file' /></div>*/_createInput: function () {var self = this;var input = document.createElement("input");input.setAttribute('type', 'file');input.setAttribute('name', this._);addStyles(input, {'position': 'absolute',// in Opera only 'browse' button// is clickable and it is located at// the right side of the input'right': 0,'margin': 0,'padding': 0,'fontSize': '480px',var div = document.createElement("div");addStyles(div, {'display': 'block','position': 'absolute','overflow': 'hidden','margin': 0,'padding': 0,'opacity': 0,// Make sure browse button is in the right side// in Internet Explorer'direction': 'ltr',//Max zIndex supported by Opera 9.0-9.2'zIndex': 2147483583});// Make sure that element opacity exists.// Otherwise use IE filterif (div.style.opacity !== "0") {if (typeof(div.filters) == 'undefined') {throw new Error('Opacity not supported by the browser');}div.style.filter = "alpha(opacity=0)";}addEvent(input, 'change', function () {if (!input || input.value === '') {return;}// Get filename from input, required// as some browsers have path instead of itvar file = fileFromPath(input.value);if (false === self._settings.onChange.call(self, file, getExt(file))) { self._clearInput();return;}// Submit form when value is changedif (self._settings.autoSubmit) {self.submit();}});addEvent(input, 'mouseover', function () {addClass(self._button, self._settings.hoverClass);});addEvent(input, 'mouseout', function () {removeClass(self._button, self._settings.hoverClass);// We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it// has display none when user selects a fileinput.parentNode.style.visibility = 'hidden';});div.appendChild(input);document.body.appendChild(div);this._input = input;},_clearInput: function () {if (!this._input) {return;}// this._input.value = ''; Doesn't work in IE6removeNode(this._input.parentNode);this._input = null;this._createInput();/*** Function makes sure that when user clicks upload button,* the this._input is clicked instead*/_rerouteClicks: function () {var self = this;// IE will later display 'access denied' error// if you use using self._input.click()// other browsers just ignore click()addEvent(self._button, 'mouseover', function () {if (self._disabled) {return;}if (!self._input) {self._createInput();}var div = self._input.parentNode;copyLayout(self._button, div);div.style.visibility = 'visible';});// commented because we now hide input on mouseleave/*** When the window is resized the elements* can be misaligned if button position depends* on window size*///addResizeEvent(function(){// if (self._input){// copyLayout(self._button, self._input.parentNode);// }//});},/*** Creates iframe with unique name* @return {Element} iframe*/_createIframe: function () {// We can't use getTime, because it sometimes return// same value in safari :(var id = getUID();// We can't use following code as the name attribute// won't be properly registered in IE6, and new window// on form submit will open// var iframe = document.createElement('iframe');// iframe.setAttribute('name', id);var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />'); // src="javascript:false; was added// because it possibly removes ie6 prompt// "This page contains both secure and nonsecure items"// Anyway, it doesn't do any harm.iframe.setAttribute('id', id);iframe.style.display = 'none';document.body.appendChild(iframe);return iframe;},/*** Creates form, that will be submitted to iframe* @param {Element} iframe Where to submit* @return {Element} form*/_createForm: function (iframe) {// var form = document.createElement('form');// form.setAttribute('method', 'post');// form.setAttribute('enctype', 'multipart/form-data');// Because in this case file won't be attached to requestvar form = toElement('<form method="post" enctype="multipart/form-data"></form>');form.setAttribute('action', settings.action);form.setAttribute('target', );form.style.display = 'none';document.body.appendChild(form);// Create hidden input element for each data keyfor (var prop in settings.data) {if (settings.data.hasOwnProperty(prop)) {var el = document.createElement("input");el.setAttribute('type', 'hidden');el.setAttribute('name', prop);el.setAttribute('value', settings.data[prop]);form.appendChild(el);}}return form;},/*** Gets response from iframe and fires onComplete event when ready* @param iframe* @param file Filename to use in onComplete callback*/_getResponse: function (iframe, file) {// getting responsevar toDeleteFlag = false,self = this,settings = this._settings;addEvent(iframe, 'load', function () {if ( // For Safariiframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||// For FF, IEiframe.src == "javascript:'<html></html>';") {// First time around, do not delete.// We reload to blank page, so that reloading main page// does not re-submit the post.if (toDeleteFlag) {// Fix busy state in FF3setTimeout(function () {removeNode(iframe);},0);}return;}var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document; // fixing Opera 9.26,10.00if (doc.readyState && doc.readyState != 'complete') {// Opera fires load event multiple times// Even when the DOM is not ready yet// this fix should not affect other browsersreturn;}// fixing Opera 9.64if (doc.body && doc.body.innerHTML == "false") {// In Opera 9.64 event was fired second time// when body.innerHTML changed from false// to server response approx. after 1 secreturn;}// response is a xml document Internet Explorer propertyresponse = doc.XMLDocument;} else if (doc.body) {// response is html document or plain textresponse = doc.body.innerHTML;if (settings.responseType && settings.responseType.toLowerCase() == 'json') {// If the document was sent as 'application/javascript' or// 'text/javascript', then the browser wraps the text in a <pre>// tag and performs html encoding on the contents. In this case,// we need to pull the original text content from the text node's// nodeValue property to retrieve the unmangled content.// Note that IE6 only understands text/htmlif (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') { response = doc.body.firstChild.firstChild.nodeValue;}if (response) {response = eval("(" + response + ")");} else {response = {};}}} else {// response is a xml documentresponse = doc;}settings.onComplete.call(self, file, response);// Reload blank page, so that reloading main page// does not re-submit the post. Also, remember to// delete the frametoDeleteFlag = true;// Fix IE mixed content issueiframe.src = "javascript:'<html></html>';";});},/*** Upload file contained in this._input*/submit: function () {var self = this,settings = this._settings;if (!this._input || this._input.value === '') {return;}var file = fileFromPath(this._input.value);// user returned false to cancel uploadif (false === settings.onSubmit.call(this, file, getExt(file))) {this._clearInput();return;}// sending requestvar iframe = this._createIframe();var form = this._createForm(iframe);// assuming following structure// div -> input type='file'removeNode(this._input.parentNode);removeClass(self._button, self._settings.hoverClass);form.appendChild(this._input);form.submit();// request set, clean upremoveNode(form);// Get response from iframe and fire onComplete event when readythis._getResponse(iframe, file);// get ready for next requestthis._createInput();}};})();以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

使用Promise封装ajax上传文件

使用Promise封装ajax上传文件

使用Promise封装ajax上传文件在使用Promise封装ajax上传文件前,我们首先要了解一下Promise的概念和使用方法。

Promise是JavaScript中的一个异步处理的对象,它可以代表一个异步操作的最终完成或失败,并返回结果或错误。

Promise有三种状态:pending(等待态)、fulfilled(成功态)和rejected(失败态)。

1. 创建一个Promise对象:```javascriptfunction uploadFile(file)return new Promise(function(resolve, reject)// 在这里进行ajax上传文件的操作});```2. 使用XMLHttpRequest对象进行文件上传:```javascriptfunction uploadFile(file)return new Promise(function(resolve, reject)var xhr = new XMLHttpRequest(;xhr.open('POST', 'upload.php', true);xhr.onload = functioif (xhr.status === 200)resolve(xhr.responseText);} elsereject(xhr.statusText);}};xhr.onerror = functioreject(xhr.statusText);};xhr.send(file);});```在上述代码中,我们创建了一个XMLHttpRequest对象,并在其`open`方法中指定了上传文件的URL和请求方式。

然后定义了`onload`事件处理函数,在文件上传完成时检查返回的状态码。

如果状态码为200,则表示上传成功,调用resolve方法返回上传的响应文本;否则,调用reject方法返回错误信息。

AjaxUpLoad.js实现文件上传功能

AjaxUpLoad.js实现文件上传功能

AjaxUpLoad.js实现⽂件上传功能AjaxUpLoad.js的使⽤实现⽆刷新⽂件上传,如图。

图1 ⽂件上传前图2 ⽂件上传后1、创建页⾯并编写HTML上传⽂档:<div class="uploadFile"><span id="doc"><input type="text" disabled="disabled" /></span><input type="hidden" id="hidFileName" /><input type="button" id="btnUploadFile" value="上传" /><input type="button" id="btnDeleteFile" value="删除" /></div>上传图⽚:<div class="uploadImg"><img id="imgShow" src="/images/nophoto.gif" /><input type="hidden" id="hidImgName" /><input type="button" id="btnUploadImg" value="上传" /><input type="button" id="btnDeleteImg" value="删除" /></div>2、引⽤AjaxUpload.js⽂件<script src="/js/common/AjaxUpload.js" type="text/javascript"></script>3、编写JS脚本window.onload = function() {init(); //初始化}//初始化function init() {//初始化⽂档上传var btnFile = document.getElementById("btnUploadFile");var doc = document.getElementById("doc");var hidFileName = document.getElementById("hidFileName");document.getElementById("btnDeleteFile").onclick = function() { DelFile(doc, hidFileName); };g_AjxUploadFile(btnFile, doc, hidFileName);//初始化图⽚上传var btnImg = document.getElementById("btnUploadImg");var img = document.getElementById("imgShow");var hidImgName = document.getElementById("hidImgName");document.getElementById("btnDeleteImg").onclick = function() { DelImg(img, hidImgName); };g_AjxUploadImg(btnImg, img, hidImgName);}var g_AjxTempDir = "/file/temp/";//⽂档上传function g_AjxUploadFile(btn, doc, hidPut, action) {var button = btn, interval;new AjaxUpload(button, {action: ((action == null || action == undefined) ? '/Common/UploadHandler.ashx?fileType=file' : action),data: {},name: 'myfile',onSubmit: function(file, ext) {if (!(ext && /^(rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|RAR|ZIP|PDF|PDFX|TXT|CSV|XLS|XLSX|DOC|DOCX)$/.test(ext))) {alert("您上传的⽂档格式不对,请重新选择!");return false;}},onComplete: function(file, response) {flagValue = response;if (flagValue == "1") {alert("您上传的⽂档格式不对,请重新选择!");}else if (flagValue == "2") {alert("您上传的⽂档⼤于2M,请重新选择!");}else if (flagValue == "3") {alert("⽂档上传失败!");}else {hidPut.value = response;doc.innerHTML="<a href='" + g_AjxTempDir + response + "' target='_blank'>" + response + "</a>";}}});}//图⽚上传function g_AjxUploadImg(btn, img, hidPut) {var button = btn, interval;new AjaxUpload(button, {action: '/Common/UploadHandler.ashx?fileType=img',data: {},name: 'myfile',onSubmit: function(file, ext) {if (!(ext && /^(jpg|JPG|png|PNG|gif|GIF)$/.test(ext))) {alert("您上传的图⽚格式不对,请重新选择!");return false;}},onComplete: function(file, response) {flagValue = response;if (flagValue == "1") {alert("您上传的图⽚格式不对,请重新选择!");}else if (flagValue == "2") {alert("您上传的图⽚⼤于200K,请重新选择!");}else if (flagValue == "3") {alert("图⽚上传失败!");}else {hidPut.value = response;img.src = g_AjxTempDir + response;}}});}//删除⽂档function DelFile(doc, hidPut) {hidPut.value = "";doc.innerHTML = "<input type=\"text\" disabled=\"disabled\" />";}//删除图⽚function DelImg(img, hidPut) {hidPut.value = "";img.src = "/images/nophoto.gif";}4、创建/Common/UploadHandler.ashx处理程序<%@ WebHandler Language="C#" Class="UploadHandler" %>using System;using System.Web;using System.Text.RegularExpressions;using System.IO;public class UploadHandler : IHttpHandler {private string _filedir = ""; //⽂件⽬录/// <summary>/// 处理上传⽂件(1:⽂件格式不正确、2:⽂件⼤⼩不正确、3:上传失败、⽂件名称:上传成功)/// </summary>/// <param name="context"></param>public void ProcessRequest (HttpContext context) {_filedir = context.Server.MapPath(@"/file/temp/");try{string result = "3";string fileType = context.Request.QueryString["fileType"]; //获取上传⽂件类型if (fileType == "file"){result = UploadFile(context); //⽂档上传}else if (fileType == "img"){result = UploadImg(context); //图⽚上传}context.Response.Write(result);}catch{context.Response.Write("3");//3⽂件上传失败}}/// <summary>/// ⽂档上传/// </summary>/// <param name="context"></param>/// <returns></returns>private string UploadFile(HttpContext context){int cout = context.Request.Files.Count;if (cout > 0){HttpPostedFile hpf = context.Request.Files[0];if (hpf != null){string fileExt = Path.GetExtension(hpf.FileName).ToLower();//只能上传⽂件,过滤不可上传的⽂件类型string fileFilt = ".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......";if (fileFilt.IndexOf(fileExt) <= -1){return "1";}//判断⽂件⼤⼩int length = hpf.ContentLength;if (length > 2097152){return "2";}Random rd = new Random();DateTime nowTime = DateTime.Now;string newFileName = nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + Path.GetExtension(hpf.FileName); if (!Directory.Exists(_filedir)){Directory.CreateDirectory(_filedir);}string fileName = _filedir + newFileName;hpf.SaveAs(fileName);return newFileName;}}return "3";}/// <summary>/// 图⽚上传/// </summary>/// <param name="context"></param>/// <returns></returns>private string UploadImg(HttpContext context){int cout = context.Request.Files.Count;if (cout > 0){HttpPostedFile hpf = context.Request.Files[0];if (hpf != null){string fileExt = Path.GetExtension(hpf.FileName).ToLower();//只能上传⽂件,过滤不可上传的⽂件类型string fileFilt = ".gif|.jpg|.php|.jsp|.jpeg|.png|......";if (fileFilt.IndexOf(fileExt) <= -1){return "1";}//判断⽂件⼤⼩int length = hpf.ContentLength;if (length > 204800){return "2";}Random rd = new Random();DateTime nowTime = DateTime.Now;string newFileName = nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + Path.GetExtension(hpf.FileName); if (!Directory.Exists(_filedir)){Directory.CreateDirectory(_filedir);}string fileName = _filedir + newFileName;hpf.SaveAs(fileName);return newFileName;}}return "3";}#region IHttpHandler 成员public bool IsReusable{get { throw new NotImplementedException(); }}#endregion}附件1:页⾯CSS样式/*上传⽂件*/.uploadFile{margin-bottom:10px;}/*上传图⽚*/.uploadImg{}.uploadImg img{width:102px; height:64px; border:1px solid #CCCCCC; display: block;}附件2:AjaxUpload.js⽂件/*** AJAX Upload ( /ajax-upload/ )* Copyright (c) Andris Valums* Licensed under the MIT license ( /mit-license/ )* Thanks to Gary Haran, David Mark, Corey Burns and others for contributions*/(function () {/* global window *//* jslint browser: true, devel: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true *//*** Wrapper for FireBug's console.log*/function log() {if (typeof(console) != 'undefined' && typeof(console.log) == 'function') {Array.prototype.unshift.call(arguments, '[Ajax Upload]');console.log(Array.prototype.join.call(arguments, ' '));}}/*** Attaches event to a dom element.* @param {Element} el* @param type event name* @param fn callback This refers to the passed element*/function addEvent(el, type, fn) {if (el.addEventListener) {el.addEventListener(type, fn, false);} else if (el.attachEvent) {el.attachEvent('on' + type, function () {fn.call(el);});} else {throw new Error('not supported or DOM not loaded');}}/*** Attaches resize event to a window, limiting* number of event fired. Fires only when encounteres* delay of 100 after series of events.** Some browsers fire event multiple times when resizing* /dom/events/resize.html** @param fn callback This refers to the passed element*/function addResizeEvent(fn) {var timeout;addEvent(window, 'resize', function () {if (timeout) {clearTimeout(timeout);}timeout = setTimeout(fn, 100);});}// Needs more testing, will be rewriten for next version// getOffset function copied from jQuery lib (/)if (document.documentElement.getBoundingClientRect) {// Get Offset using getBoundingClientRect// /blog/getboundingclientrect-is-awesome/var getOffset = function (el) {var box = el.getBoundingClientRect();var doc = el.ownerDocument;var body = doc.body;var docElem = doc.documentElement; // for ievar clientTop = docElem.clientTop || body.clientTop || 0;var clientLeft = docElem.clientLeft || body.clientLeft || 0;// In Internet Explorer 7 getBoundingClientRect property is treated as physical,// while others are logical. Make all logical, like in IE8.var zoom = 1;if (body.getBoundingClientRect) {var bound = body.getBoundingClientRect();zoom = (bound.right - bound.left) / body.clientWidth;}if (zoom > 1) {clientTop = 0;clientLeft = 0;}var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;return {top: top,left: left};};} else {// Get offset adding all offsetsvar getOffset = function (el) {var top = 0,left = 0;do {top += el.offsetTop || 0;left += el.offsetLeft || 0;el = el.offsetParent;} while (el);return {left: left,top: top};};}/*** Returns left, top, right and bottom properties describing the border-box,* in pixels, with the top-left relative to the body* @param {Element} el* @return {Object} Contains left, top, right,bottom*/function getBox(el) {var left, right, top, bottom;var offset = getOffset(el);left = offset.left;top = offset.top;right = left + el.offsetWidth;bottom = top + el.offsetHeight;return {left: left,right: right,top: top,bottom: bottom};}/*** Helper that takes object literal* and add all properties to element.style* @param {Element} el* @param {Object} styles*/function addStyles(el, styles) {for (var name in styles) {if (styles.hasOwnProperty(name)) {el.style[name] = styles[name];}}}/*** Function places an absolutely positioned* element on top of the specified element* copying position and dimentions.* @param {Element} from* @param {Element} to*/function copyLayout(from, to) {var box = getBox(from);addStyles(to, {position: 'absolute',left: box.left + 'px',top: box.top + 'px',width: from.offsetWidth + 'px',height: from.offsetHeight + 'px'});}/*** Creates and returns element from html chunk* Uses innerHTML to create an element*/var toElement = (function () {var div = document.createElement('div');return function (html) {div.innerHTML = html;var el = div.firstChild;return div.removeChild(el);};})();/*** Function generates unique id*/var getUID = (function () {var id = 0;return function () {return 'ValumsAjaxUpload' + id++;};})();/*** Get file name from path* @param {String} file path to file* @return filename*/function fileFromPath(file) {return file.replace(/.*(\/|\\)/, "");}/*** Get file extension lowercase* @param {String} file name* @return file extenstion*/function getExt(file) {return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';}function hasClass(el, name) {var re = new RegExp('\\b' + name + '\\b');return re.test(el.className);}function addClass(el, name) {if (!hasClass(el, name)) {el.className += ' ' + name;}}function removeClass(el, name) {var re = new RegExp('\\b' + name + '\\b');el.className = el.className.replace(re, '');}function removeNode(el) {el.parentNode.removeChild(el);}/*** Easy styling and uploading* @constructor* @param button An element you want convert to* upload button. Tested dimentions up to 500x500px* @param {Object} options See defaults below.*/window.AjaxUpload = function (button, options) {this._settings = {// Location of the server-side upload scriptaction: 'upload.php',// File upload namename: 'userfile',// Additional data to senddata: {},// Submit file as soon as it's selectedautoSubmit: true,// The type of data that you're expecting back from the server.// html and xml are detected automatically.// Only useful when you are using json data as a response.// Set to "json" in that case.responseType: false,// Class applied to button when mouse is hoveredhoverClass: 'hover',// Class applied to button when AU is disableddisabledClass: 'disabled',// When user selects a file, useful with autoSubmit disabled// You can return false to cancel uploadonChange: function (file, extension) {},// Callback to fire before file is uploaded// You can return false to cancel uploadonSubmit: function (file, extension) {},// Fired when file upload is completed// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!onComplete: function (file, response) {}};// Merge the users options with our defaultsfor (var i in options) {if (options.hasOwnProperty(i)) {this._settings[i] = options[i];}}// button isn't necessary a dom elementif (button.jquery) {// jQuery object was passedbutton = button[0];} else if (typeof button == "string") {if (/^#.*/.test(button)) {// If jQuery user passes #elementId don't break itbutton = button.slice(1);}button = document.getElementById(button);}if (!button || button.nodeType !== 1) {throw new Error("Please make sure that you're passing a valid element"); }if (button.nodeName.toUpperCase() == 'A') {// disable linkaddEvent(button, 'click', function (e) {if (e && e.preventDefault) {e.preventDefault();} else if (window.event) {window.event.returnValue = false;}});}// DOM elementthis._button = button;this._input = null;// If disabled clicking on button won't do anythingthis._disabled = false;// if the button was disabled before refresh if will remain// disabled in FireFox, let's fix itthis.enable();this._rerouteClicks();};// assigning methods to our classAjaxUpload.prototype = {setData: function (data) {this._settings.data = data;},disable: function () {addClass(this._button, this._settings.disabledClass);this._disabled = true;var nodeName = this._button.nodeName.toUpperCase();if (nodeName == 'INPUT' || nodeName == 'BUTTON') {this._button.setAttribute('disabled', 'disabled');}// hide inputif (this._input) {// We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it// has display none when user selects a filethis._input.parentNode.style.visibility = 'hidden';}},enable: function () {removeClass(this._button, this._settings.disabledClass);this._button.removeAttribute('disabled');this._disabled = false;},/*** Creates invisible file input* that will hover above the button* <div><input type='file' /></div>*/_createInput: function () {var self = this;var input = document.createElement("input");input.setAttribute('type', 'file');input.setAttribute('name', this._);addStyles(input, {'position': 'absolute',// in Opera only 'browse' button// is clickable and it is located at// the right side of the input'right': 0,'margin': 0,'padding': 0,'fontSize': '480px','cursor': 'pointer'});var div = document.createElement("div");addStyles(div, {'display': 'block','position': 'absolute','overflow': 'hidden','margin': 0,'padding': 0,'opacity': 0,// Make sure browse button is in the right side// in Internet Explorer'direction': 'ltr',//Max zIndex supported by Opera 9.0-9.2'zIndex': 2147483583});// Make sure that element opacity exists.// Otherwise use IE filterif (div.style.opacity !== "0") {if (typeof(div.filters) == 'undefined') {throw new Error('Opacity not supported by the browser');}div.style.filter = "alpha(opacity=0)";}addEvent(input, 'change', function () {if (!input || input.value === '') {return;}// Get filename from input, required// as some browsers have path instead of itvar file = fileFromPath(input.value);if (false === self._settings.onChange.call(self, file, getExt(file))) { self._clearInput();return;}// Submit form when value is changedif (self._settings.autoSubmit) {self.submit();}});addEvent(input, 'mouseover', function () {addClass(self._button, self._settings.hoverClass);});addEvent(input, 'mouseout', function () {removeClass(self._button, self._settings.hoverClass);// We use visibility instead of display to fix problem with Safari 4 // The problem is that the value of input doesn't change if it// has display none when user selects a fileinput.parentNode.style.visibility = 'hidden';});document.body.appendChild(div);this._input = input;},_clearInput: function () {if (!this._input) {return;}// this._input.value = ''; Doesn't work in IE6removeNode(this._input.parentNode);this._input = null;this._createInput();removeClass(this._button, this._settings.hoverClass);},/*** Function makes sure that when user clicks upload button,* the this._input is clicked instead*/_rerouteClicks: function () {var self = this;// IE will later display 'access denied' error// if you use using self._input.click()// other browsers just ignore click()addEvent(self._button, 'mouseover', function () {if (self._disabled) {return;}if (!self._input) {self._createInput();}var div = self._input.parentNode;copyLayout(self._button, div);div.style.visibility = 'visible';});// commented because we now hide input on mouseleave/*** When the window is resized the elements* can be misaligned if button position depends* on window size*///addResizeEvent(function(){// if (self._input){// copyLayout(self._button, self._input.parentNode);// }//});},/*** Creates iframe with unique name* @return {Element} iframe*/_createIframe: function () {// We can't use getTime, because it sometimes return// same value in safari :(var id = getUID();// We can't use following code as the name attribute// won't be properly registered in IE6, and new window// on form submit will open// var iframe = document.createElement('iframe');// iframe.setAttribute('name', id);var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');// src="javascript:false; was added// because it possibly removes ie6 prompt// "This page contains both secure and nonsecure items"// Anyway, it doesn't do any harm.iframe.setAttribute('id', id);iframe.style.display = 'none';document.body.appendChild(iframe);return iframe;},/*** Creates form, that will be submitted to iframe* @param {Element} iframe Where to submit* @return {Element} form*/_createForm: function (iframe) {var settings = this._settings;// We can't use the following code in IE6// var form = document.createElement('form');// form.setAttribute('method', 'post');// form.setAttribute('enctype', 'multipart/form-data');// Because in this case file won't be attached to requestvar form = toElement('<form method="post" enctype="multipart/form-data"></form>'); form.setAttribute('action', settings.action);form.setAttribute('target', );form.style.display = 'none';document.body.appendChild(form);// Create hidden input element for each data keyfor (var prop in settings.data) {if (settings.data.hasOwnProperty(prop)) {var el = document.createElement("input");el.setAttribute('type', 'hidden');el.setAttribute('name', prop);el.setAttribute('value', settings.data[prop]);form.appendChild(el);}}return form;},/*** Gets response from iframe and fires onComplete event when ready* @param iframe* @param file Filename to use in onComplete callback*/_getResponse: function (iframe, file) {// getting responseself = this,settings = this._settings;addEvent(iframe, 'load', function () {if ( // For Safariiframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||// For FF, IEiframe.src == "javascript:'<html></html>';") {// First time around, do not delete.// We reload to blank page, so that reloading main page// does not re-submit the post.if (toDeleteFlag) {// Fix busy state in FF3setTimeout(function () {removeNode(iframe);},0);}return;}var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document; // fixing Opera 9.26,10.00if (doc.readyState && doc.readyState != 'complete') {// Opera fires load event multiple times// Even when the DOM is not ready yet// this fix should not affect other browsersreturn;}// fixing Opera 9.64if (doc.body && doc.body.innerHTML == "false") {// In Opera 9.64 event was fired second time// when body.innerHTML changed from false// to server response approx. after 1 secreturn;}var response;if (doc.XMLDocument) {// response is a xml document Internet Explorer propertyresponse = doc.XMLDocument;} else if (doc.body) {// response is html document or plain textresponse = doc.body.innerHTML;if (settings.responseType && settings.responseType.toLowerCase() == 'json') {// If the document was sent as 'application/javascript' or// 'text/javascript', then the browser wraps the text in a <pre>// tag and performs html encoding on the contents. In this case,// we need to pull the original text content from the text node's// nodeValue property to retrieve the unmangled content.// Note that IE6 only understands text/htmlif (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {response = doc.body.firstChild.firstChild.nodeValue;}if (response) {response = eval("(" + response + ")");} else {response = {};}}} else {// response is a xml documentresponse = doc;}settings.onComplete.call(self, file, response);// Reload blank page, so that reloading main page// does not re-submit the post. Also, remember to// delete the frametoDeleteFlag = true;// Fix IE mixed content issueiframe.src = "javascript:'<html></html>';";});},/*** Upload file contained in this._input*/submit: function () {var self = this,settings = this._settings;if (!this._input || this._input.value === '') {return;}var file = fileFromPath(this._input.value);// user returned false to cancel uploadif (false === settings.onSubmit.call(this, file, getExt(file))) {this._clearInput();return;}// sending requestvar iframe = this._createIframe();var form = this._createForm(iframe);// assuming following structure// div -> input type='file'removeNode(this._input.parentNode);removeClass(self._button, self._settings.hoverClass);form.appendChild(this._input);form.submit();// request set, clean upremoveNode(form);form = null;removeNode(this._input);this._input = null;// Get response from iframe and fire onComplete event when readythis._getResponse(iframe, file);// get ready for next requestthis._createInput();}};})();以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

AjaxFileUpload.js实现异步上传文件功能

AjaxFileUpload.js实现异步上传文件功能

AjaxFileUpload.js实现异步上传⽂件功能做软⼯作业时,需要实现⽆刷新异步上传图⽚到服务器,于是想利⽤Ajax:得到file的val,再post过去…等真正实现的时候才发现,根本⾏不通。

于是翻来翻去找到⼀个封装好的js插件,可以实现异步上传⽂件。

AjaxFileUpload这个插件的原理是创建隐藏的表单和iframe,然后⽤JS去提交,获得返回值。

语法$.ajaxFileUpload([options])参数说明url 上传处理程序地址。

fileElementId 需要上传的⽂件域的ID,即的ID。

secureuri 是否启⽤安全提交,默认为false。

dataType 服务器返回的数据类型。

可以为xml,script,json,html。

如果不填写,jQuery会⾃动判断。

success 提交成功后⾃动执⾏的处理函数,参数data就是服务器返回的数据。

error 提交失败⾃动执⾏的处理函数。

data ⾃定义参数。

这个东西⽐较有⽤,当有数据是与上传的图⽚相关的时候,这个东西就要⽤到了。

type 当要提交⾃定义参数时,这个参数要设置成post使⽤⽅法引⼊jQuery与ajaxFileUpload插件(由api中⼼强⼒提供)<script type="text/javascript" src="https:///js/jquery.min.js"></script><script type="text/javascript" src="https:///js/ajaxfileupload.js"></script>扩展HTML代码<td height="52" class="inputContent" ><div align="center">附件1<input type="file" name="upload_file" id="ss_upload_file1"></td><td colspan="3"><input type="button" name="Submit3" value="上传" class="button" id="ss_file_upload"></td>JS代码$("#ss_file_upload").click(function(){$.ajaxFileUpload({url:'doajaxfileupload.php',//请求地址secureuri:false,//是否需要安全协议fileElementId:'ss_upload_file1',//file的IDdataType: 'text',//返回值类型,⼀般为jsonsuccess: function(img_data1)//成功后执⾏{$(ss_file1_url).attr("value",img_data1);alert("上传成功");},error:function(img_data1,status,e){alert("上传失败");}})})PHP代码后台就是进⾏上传操作啦,因为是课程设计所以我将图⽚上传到了七⽜云存储中。

使用AJAX实现上传文件

使用AJAX实现上传文件

使⽤AJAX实现上传⽂件本⽂实例为⼤家分享了使⽤AJAX实现上传⽂件的具体代码,供⼤家参考,具体内容如下需求:在前端页⾯选择⽂件上传到服务器的指定位置前端代码<form id="uploadForm" method="post" enctype="multipart/form-data"><label >上传电⼦书</label><input type="file" name="file" ><button id="upload" type="button" name="button" >上传</button></form>$("#upload").click(function () {var formData = new FormData($('#uploadForm')[0]);$.ajax({type: 'post',url: "https://****:8443/fileUpload", //上传⽂件的请求路径必须是绝对路劲data: formData,cache: false,processData: false,contentType: false,}).success(function (data) {console.log(data);alert("上传成功"+data);filename=data;}).error(function () {alert("上传失败");});});⾸先创建⼀个FormData实例,也就是空对象,将页⾯中现有form表单将他初始化。

文件上传(用ajaxfileupload这个js插件)

文件上传(用ajaxfileupload这个js插件)

文件上传(用ajaxfileupload这个js插件)<p>#buttonupload{width:61px;}session_start();$servername='192.168.1.111';$error=\$msg=\$suffix=\$isuname=\$fileelementname='file';$imginfo=null;if(!empty($_files[$fileelementname]['error'])){switch($_files[$fileelementname]['error']){case'1':$error='theuploadedfileexceedstheupload_max_filesizedirectiveinphp.ini';break; case'2':$error='theuploadedfileexceedsthemax_file_sizedirectivethatwasspecifiedintheht mlform';break;case'3':$error='theuploadedfilewasonlypartiallyuploaded';break;case'4':$error='nofilewasuploaded.';break;case'6':$error='missingatemporaryfolder';break;case'7':$error='failedtowritefiletodisk';break;case'8':$error='fileuploadstoppedbyextension';break;case'999':default:$error='noerrorcodeavaiable';}}elseif(empty($_files['file']['tmp_name'])||$_files['file']['tmp_name']==' none'){$error='nofilewasuploaded..';}else{//$msg.=\//$msg.=\@filesize($_files['file']['tmp_name']);//move_uploaded_file($_files['file']['tmp_name'],'../resource/'.$_files['filet oupload']['name']);//forsecurityreason,weforcetoremovealluploadedfile//@unlink($_files['filetoupl oad']);//保存上传文件(图片:gif、swf、jpg)if((($_files[\||($_files[\||($_files[\||($_files[\&&($_files[\mb_internal_enco ding('utf-8');$suffix=mb_substr($_files['file']['name'],mb_strripos($_files['file']['name'], '.'));$filename=md5(uniqid().microtime(true)).$suffix;move_uploaded_file($_files[\resource/\//if(file_exists(\////$isuname=$_files[\已经存在。

js实现ajax发送步骤过程详解

js实现ajax发送步骤过程详解

js实现ajax发送步骤过程详解js发送ajax发送,分步骤进⾏ajax的核⼼是XMLHttpRequest,步骤1:创建⼀个对象xmlrequest,在主流的浏览器都⽀持new ,var xmlhttp = new XMLHttpRequest() IE浏览器不⽀持这种⽅法,需要再写⼀个函数来创建步骤2 :连接服务端得到XMLHTTPRequest对象后,就可以调⽤对象的open()⽅法,与服务器连接,参数如下open(method,url,async):method:请求⽅法GET或POST,url:服务器的地址,async :表⽰异步请求,可以不写,默认是True,xmlhttp.open("GET“,"/ajax_get/",true);步骤3:发送请求xmlhtto.send(null),有兼容的问题,加上null, null在js中⼀种数据类型,表⽰空,以上3个步骤相当于jquery的$.ajax({ url:"/ajax_get/", type:"GET", success:function(){ } )}步骤4:接收服务器响应,请求发出,服务端开始执⾏,XMLHttpRequest对象有⼀个onreadystatechange事件,0:初始化外⽹状态,只创建XMLHttpRequest对象,1:请求开始,open( )⽅法调⽤,2:请求发送完成状态,send()⽅法调⽤,3:开始读取服务器响应,4:读取服务器响应结束,onreadystatechange 事件会在状态为1,2,3,4 时引发,<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Title</title></head><body><form action="/index/" method="post"><p><input type="text">{{ error }}</p><p><input type="text">{{ error }}</p><p><input type="submit"></p></form><p>⽤户名:<input type="text" class="user"></p><button onclick="send()">ajax</button></body><script>{# 给button按钮绑定send事件#}function send() {var ele = document.getElementsByClassName("user")[0];var con = ele.valueOf;xmlHttp=new XMLHttpRequest();xmlHttp.open("GET","/getajax/",true);xmlHttp.send(null);{#监听服务端 #}xmlHttp.onreadystatechange=function () {if (xmlHttp.readyState ==4 && xmlHttp.status ==200){alert(xmlHttp.responseText);alert(typeof xmlHttp.responseText)}}}通过XMLHttpRequest对象的readyState属性来得到XMLHttpRequest对象的状态。

Ajax实现文件上传功能(SpringMVC)

Ajax实现文件上传功能(SpringMVC)

Ajax实现⽂件上传功能(SpringMVC)本⽂实例为⼤家分享了Ajax实现⽂件上传的具体代码,供⼤家参考,具体内容如下前端表单和 JQuery jsp/html代码使⽤JQury<script src="static/js/jquery-3.4.1.js"></script>前端表单<form id="form-avatar" enctype="multipart/form-data"><p>请选择要上传的⽂件:</p><p><input type="file" name="file" /></p><p><input id="btn-avatar" type="button" value="上传" /></p></form>ajax请求服务器<script>function uploadfile(){$.ajax({url : "/url/upload",data: new FormData($("#form-avatar")[0]),type : "POST",// 告诉jQuery不要去处理发送的数据,⽤于对data参数进⾏序列化处理这⾥必须falseprocessData : false,// 告诉jQuery不要去设置Content-Type请求头contentType : false,success : function(json) {alert("执⾏成功");},error : function(json) {alert("执⾏失败");}});}$("#btn-avatar").on("click",uploadfile);</script>Conroller.java@PostMapping("/upload")public void fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { System.out.println("⾛了");//上传路径保存设置String path = request.getServletContext().getRealPath("/upload");File realPath = new File(path);if (!realPath.exists()) {realPath.mkdir();}//上传⽂件地址System.out.println("上传⽂件保存地址:" + realPath);//通过CommonsMultipartFile的⽅法直接写⽂件(注意这个时候)file.transferTo(new File(realPath + "/" + file.getOriginalFilename()));}结果以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

文件上传之伪Ajax方式上传

文件上传之伪Ajax方式上传

文件上传之伪Ajax方式上传最近做项目遇到了些关于上传的功能模块,在网上找了很多关于上传的相关资料,找到了一个依赖于Jquery写的jquery.uploadify类库,这个类库的上传功能支持的非常全面,不过遗憾的是它是依赖于flash来处理上传,所以在页面中呈现不了传统的上传控件的浏览方式,因为项目需求必须以传统的<input type='file'/>形态模式出现在页面中!所以只好舍去jquery.uploadify类库强大功能,于是乎自己研究了一番。

最终实现了一个静态上传的功能!好了,废话不多说,代码献上!如阁下有更好的建议欢迎强力拍砖!小弟不胜感激!首先我的后台程序用的是Javascript用到了Jquery类库这里先给大家介绍下为什么叫伪Ajax方式上传,因为这个上传不会使当前页面产生刷新的效果,并且也没有用任何的Ajax技术,但是实现了页面无刷新的上传效果,因此小弟称为伪Ajax方式。

呵呵,关子卖了很久了!介绍下这个核心吧!核心主要是利用<form>和<iframe>实现!相信对Web Html认识比较深的大虾们一定猜到个大概了吧!HTML CODE:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="/1999/xhtml"><head><title>File Upload</title></head><body><!--大家注意到这个form的target的了么?这个target属性的值frameFile,是form之后的iframe的name值,这样的写法是让当前的form表单在提交表单内容的时候转交给iframe中进行页面中表单处理,并且不会产生当前页面跳转!--><form id='formFile' name='formFile' method="post" action='/uploads.aspx' target='frameFile' enctype="multipart/form-data"><input type='file' id='fileUp' name='fileUp' /><div id='uploadLog'></div><br /><img width='200' src='' height='200' id='imgShow' alt='缩略图' /></form><!--这个iframe拿到post过来的表单数据后会开始在自身内部访问post过来的页面地址,在内部中它会刷新页面,但是这已不重要了,因为当前的iframe已经被我display:none隐藏了!所以这样给用户看起来像是无刷新的页面文件上传,其实只是做一个一个小小的技巧!--><iframe id='frameFile' name='frameFile' style=' display:none;'></iframe></body></html>JavaScript Code:<script type="text/javascript" language="javascript">$(function () {$('#fileUp').change(function () {$('#uploadLog').html('开始上传中....');$('#formFile').submit();});})function uploadSuccess(msg) {if (msg.split('|').length > 1) {$('#imgShow').attr('src', msg.split('|')[1]);$('#uploadLog').html(msg.split('|')[0]);} else {$('#uploadLog').html(msg);}}</script> Code:///<summary>///页面加载.在这里我简单的写了下文件上传的处理Code///</summary>///<param name="sender"></param>///<param name="e"></param>protected void Page_Load(object sender, EventArgs e){try{//获取当前Post过来的file集合对象,在这里我只获取了<input type='file' name='fileUp'/>的文件控件HttpPostedFile file = Request.Files["fileUp"];if (file != null){//当前文件上传的目录string path = Server.MapPath("~/Test/");//当前待上传的服务端路径string imageUrl = path + Path.GetFileName(file.FileName);//当前文件后缀名string ext = Path.GetExtension(file.FileName).ToLower();//验证文件类型是否正确if(!ext.Equals(".gif") && !ext.Equals(".jpg") && !ext.Equals(".png") && !ext.Equals(".bmp")){//这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址Response.Write("<script>window.parent.uploadSuccess('你上传的文件格式不正确!上传格式有(.gif、.jpg、.png、.bmp)');</script>");Response.End();}//验证文件的大小if (file.ContentLength > 1048576){//这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址Response.Write("<script>window.parent.uploadSuccess('你上传的文件不能大于1048576KB!请重新上传!');</script>");Response.End();}//开始上传file.SaveAs(imageUrl);//这里window.parent.uploadSuccess()是我在前端页面中写好的javascript function,此方法主要用于输出异常和上传成功后的图片地址//如果成功返回的数据是需要返回两个字符串,我在这里使用了|分隔例:成功信息|/Test/hello.jpgResponse.Write("<script>window.parent.uploadSuccess('Up load Success!|/Test/" + file.FileName + "');</script>");Response.End();}else{//上传失败Response.Write("upload lose!");Response.End();}}catch {//上传失败Response.Write("upload lose!");Response.End();}}。

WebApi实现Ajax模拟Multipartform-data方式多文件上传

WebApi实现Ajax模拟Multipartform-data方式多文件上传

WebApi实现Ajax模拟Multipartform-data⽅式多⽂件上传前端页⾯代码:<input type="file" class="file_control"/><br /><input type="file" class="file_control"/><br /><input type="file" class="file_control"/><button id="btnUpload" type="button">上传</button><script type="text/javascript">$(document).ready(function () {$("#btnUpload").click(function () {var formdata = new FormData();var files = $(".file_control");$.each(files, function (index, domEle) {formdata.append("file" + index, domEle.files[0]);});$.ajax({url: '/api/Service/UpLoad',type: 'POST',cache: false,data: formdata,processData: false,contentType: false,success: function (data) {alert(data.success);},error: function () {alert("error");}}).done(function (res) {}).fail(function (res) {});});</script>后端代码:///<summary>///⽂件上传///</summary>///<param name="request"></param>///<returns></returns>[HttpPost][Route("api/Service/UpLoad")]public Task<HttpResponseMessage> UpLoad(HttpRequestMessage request){if (!request.Content.IsMimeMultipartContent())throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);if (!ModelState.IsValid)throw new HttpResponseException(HttpStatusCode.BadRequest);string root = AppDomain.CurrentDomain.BaseDirectory + @"UploadFiles";if (!Directory.Exists(root))Directory.CreateDirectory(root);MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root);var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>{if (t.IsFaulted || t.IsCanceled)return request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);HttpResponseMessage response = null;string filePath = root + @"\" + DateTime.Now.ToString("yyyyMMdd");if (!Directory.Exists(filePath))Directory.CreateDirectory(filePath);foreach (var file in provider.FileData){string fileName = file.Headers.ContentDisposition.FileName;if (Regex.IsMatch(fileName, @"^"".*""$"))fileName = fileName.Trim('"');if (Regex.IsMatch(fileName, @"[\\/]+"))fileName = Path.GetFileName(fileName);string extName = Path.GetExtension(fileName);string tempName = DateTime.Now.Ticks.ToString() + extName;File.Copy(file.LocalFileName, bine(filePath, tempName));if (File.Exists(file.LocalFileName))File.Delete(file.LocalFileName);// 转存阿⾥OSS、七⽜云、腾讯云COSresponse = request.CreateResponse(HttpStatusCode.OK, new { success = true }); }return response;});return task;}*注:如果报IsFaulted=true的错误,基本上是因为你没给input起name造成的。

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

<!-- HTML页面内容--><?php if(isset($arr)){ ?><table border="1" width="500"><tr><th>标题:</th><th>内容:</th><th>图片:</th></tr><?php foreach($arr as $v){ ?><tr align="center"><td><?php echo $v['title'];?></td><td><?php echo $v['content'];?></td><td><img src=" <?php echo $v['path'];?> " style="width:100px; height:100px;" /></td></tr><?php } ?></table><?php } ?><br />/* 注意:表单中不能有name="submit"的标签,form中不能缺少enctype="multipart/form-data" */<form action="./upload.php?act=form" method="post" name="form1" enctype="multipart/form-data"> 标题:<input type="text" name="title" /><br />内容:<textarea name="content" rows="5" cols="50"></textarea><br />上传文件:<input type="file" name="upload" id="f" /><input type="button" value="上传" id="upload_file" onclick="uploadfile(form1)" /><input type="hidden" name="path" id="path" /><br /><iframe name="check_file_frame" id="check_file_frame" style="display:none;"></iframe> <input type="submit" value="提交" /><input type="reset" value="重置" /></form><script>var fileForm = new Object();function uploadfile(obj){var fileObj = document.getElementById('f').value;if(fileObj != ''){//把form的原始数据缓存起来fileForm.f = obj;//form.action 为一个静态的对象,所以这里要使用getAttribute方法取值fileForm.a = obj.getAttribute('action');fileForm.t = obj.target;//请求服务器端obj.target = "check_file_frame";obj.action = "./upload.php?act=file";obj.submit();}return false;}//回调函数function ajax_callback(result) {//还原form属性fileForm.f.target = fileForm.t;fileForm.f.setAttribute("action", fileForm.a);//处理结果if((typeof result)=="object"){alert(result[0]);document.getElementById('path').value = result[1];}else{alert(result);}}</script><!-- php页面内容--><?phpswitch($_GET['act']){case 'file':if(!$_FILES['upload'] || !is_array($_FILES['upload']))exit("<script>parent.ajax_callback('您没有选择要上传的文件');</script>");if(!$_FILES['upload']['size'])exit("<script>parent.ajax_callback('空文件上传');</script>");if($_FILES['upload']['size']>1024*1024*2)exit("<script>parent.ajax_callback('上传文件太大');</script>");$ext_name = substr($_FILES['upload']['name'],strrpos($_FILES['upload']['name'],'.')+1);if(!preg_match('/^(jpg|jpeg|gif|png|pdf|doc|xls|txt|rar|zip|tar)$/i',$ext_name))exit("<script>parent.ajax_callback('不允许上传'.$ext_name.' 格式的文件');</script>");$path = dirname(__FILE__).'/upload/';if(!file_exists($path)) @mkdir($path,0777,true);if(!file_exists($path)) exit("<script>parent.ajax_callback('不能创建上传文件的目标路径');</script>"); $path = $path.date('ymd_H_i_s_').rand().'.'.$ext_name;if(is_uploaded_file($_FILES['upload']['tmp_name']) &&(@move_uploaded_file($_FILES['upload']['tmp_name'],$path) ||@copy($_FILES['upload']['tmp_name'],$path))){@chmod($path,0777);$arr = array('上传成功',$path);exit("<script>parent.ajax_callback(".json_encode($arr).");</script>");}else{exit("<script>parent.ajax_callback('上传失败');</script>");}break;case 'form':$arr['info']['title'] = $_POST['title'];$arr['info']['content'] = $_POST['content'];$arr['info']['path'] = './upload/'.basename($_POST['path']); include './upload.html';break;}。

相关文档
最新文档