b2c信息网

您现在的位置是:首页 > 热点问题 > 正文

热点问题

ajax上传大文件源码(ajax上传文件)

hacker2022-08-21 06:20:25热点问题66
本文目录一览:1、用ajax上传最大就是20M,有什么办法可以控制上传文件的大小,传多大的文件都可以

本文目录一览:

用ajax上传最大就是20M,有什么办法可以控制上传文件的大小,传多大的文件都可以

这个要看你的ajax插件代码了,应该有个类似:maxFileSize的属性控制,找到这个属性值,改大点,或者把这个判断取消掉

PHP 如何用ajax做文件上传

通过传统的form表单提交的方式上传文件:

[html] view plain copy 在CODE上查看代码片派生到我的代码片form id= "uploadForm" action= "" method= "post" enctype ="multipart/form-data"

h1 测试通过Rest接口上传文件 /h1

p 指定文件名: input type ="text" name="filename" //p

p 上传文件: input type ="file" name="file" //p

p 关键字1: input type ="text" name="keyword" //p

p 关键字2: input type ="text" name="keyword" //p

p 关键字3: input type ="text" name="keyword" //p

input type ="submit" value="上传"/

/form

不过传统的form表单提交会导致页面刷新,但是在有些情况下,我们不希望页面被刷新,这种时候我们都是使用Ajax的方式进行请求的。

Ajax的方式进行请求:

[javascript] view plain copy 在CODE上查看代码片派生到我的代码片$.ajax({

url : "",type : "POST",

data : $( '#postForm').serialize(),

success : function(data) {

$( '#serverResponse').html(data);

},

error : function(data) {

$( '#serverResponse').html(data.status + " : " + data.statusText + " : " + data.responseText);}

});

通常我们提交(使用submit button)时,会把form中的所有表格元素的name与value组成一个queryString,提交到后台。这用jQuery的方法来说,就是serialize。

通过$('#postForm').serialize()可以对form表单进行序列化,从而将form表单中的所有参数传递到服务端。

但是上述方式,只能传递一般的参数,上传文件的文件流是无法被序列化并传递的。

不过如今主流浏览器都开始支持一个叫做FormData的对象,有了这个FormData,我们就可以轻松地使用Ajax方式进行文件上传了。

关于FormData及其用法

FormData是什么呢?我们来看看Mozilla上的介绍。

XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个"表单".比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.

所有主流浏览器的较新版本都已经支持这个对象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。

参见:

FormData()

想得到一个FormData对象:

var formdata = new FormData();

W3c草案提供了三种方案来获取或修改FormData。

方案1:创建一个空的FormData对象,然后再用append方法逐个添加键值对:

var formdata = new FormData();

formdata.append("name", "呵呵");

formdata.append("url", "");方案2:取得form元素对象,将它作为参数传入FormData对象中!

var formobj = document.getElementById("form");var formdata = new FormData(formobj);

方案3:利用form元素对象的getFormData方法生成它!

var formobj = document.getElementById("form");var formdata = formobj.getFormData()

Method

FormData.append

本方法用于向已存在的键添加新的值,如该键不存在,新建之。

语法

formData.append(name, value);

formData.append(name, value, filename);

注: 通过 FormData.append()方法赋给字段的值若是数字会被自动转换为字符(字段的值可以是一个Blob对象,一个File对象,或者一个字符串,剩下其他类型的值都会被自动转换成字符串).

参数解释

name

键 (key), 对应表单域

value

表单域的值

filename (optional)

The filename reported to the server (a USVString), when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob".

FormData.delete

将一对键和值从 FormData 对象中删除。

formData.delete(username);

FormData.get

返回给定键的第一个值

formData.append('username', 'Justin');

formData.append('username', 'Chris');

formData.get(username); // "Justin"

FormData.getAll

返回给定键的所有值

formData.append('username', 'Justin');

formData.append('username', 'Chris');

formData.getAll(username); // ["Justin", "Chris"]

FormData.has

检查是否包含给定键,返回 true 或 false

formData.has(username);

FormData.set

设置给定键的值

formData.set(name, value);

formData.set(name, value, filename);

浏览器兼容情况

来自 MDN:

Desktop

FeatureChromeFirfox(Gecko)Intenet ExplorerOperaSafariBasic support7+4.0(2.0)10+12+5+

append with filename(Yes)22.0(22.0)???

delete, get, getAll, has, setBehind FlagNot supportedNot supported(Yes)Not supportedMobile

FeatureAndroidChrome AndroidFirfox Mobile (Gecko)Firfox OS (Gecko)IE MobileOpera MobileSafari MobileBasic support3.0?4.0(2.0)1.0.1?12+?

append with filename??22.0(22.0)1.2???

delete, get, getAll, has, set(Yes)(Yes)Not supportedNot supportedNot supported(Yes)Not supported2015年06月04日发布

Ajax通过FormData上传文件

1.使用form表单初始化FormData对象方式上传文件HTML代码

form id="uploadForm" enctype="multipart/form-data"

input id="file" type="file" name="file"/

button id="upload" type="button"upload/button

/form

javascript代码

$.ajax({

url: '/upload',

type: 'POST',

cache: false,

data: new FormData($('#uploadForm')[0]),

processData: false,

contentType: false

}).done(function(res) {

}).fail(function(res) {});

这里要注意几点:

processData设置为false。因为data值是FormData对象,不需要对数据做处理。

form标签添加enctype="multipart/form-data"属性。

cache设置为false,上传文件不需要缓存。

contentType设置为false,不设置contentType值,因为是由form表单构造的FormData对象,且已经声明了属性enctype="multipart/form-data",所以这里设置为false。

上传后,服务器端代码需要使用从查询参数名为file获取文件输入流对象,因为input中声明的是name="file"。

如果不是用form表单构造FormData对象又该怎么做呢?

2.使用FormData对象添加字段方式上传文件

HTML代码

div id="uploadForm"

input id="file" type="file"/

button id="upload" type="button"upload/button

/div

这里没有form标签,也没有enctype="multipart/form-data"属性。

javascript代码

var formData = new FormData();

formData.append('file', $('#file')[0].files[0]);$.ajax({

url: '/upload',

type: 'POST',

cache: false,

data: formData,

processData: false,

contentType: false

}).done(function(res) {

}).fail(function(res) {});

这里有几处不一样:

append()的第二个参数应是文件对象,即$('#file')[0].files[0]。

contentType也要设置为‘false’。

从代码$('#file')[0].files[0]中可以看到一个input type="file"标签能够上传多个文件,只需要在input type="file"里添加multiple或multiple="multiple"属性。

3.服务器端读文件

从Servlet 3.0 开始,可以通过 request.getPart() 或 request.getPars() 两个接口获取上传的文件。

怎么样通过jQuery Ajax实现上传文件

Query Ajax在web应用开发中很常用,它主要包括有ajax,get,post,load,getscript等等这几种常用无刷新操作方法,接下来通过本文给大家介绍jquery ajax 上传文件处理方式。

FormData对象

XMLHttpRequest Level 2添加了一个新的接口FormData.利用FormData对象,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,我们还可以使用XMLHttpRequest的send()方法来异步的提交这个”表单”.比起普通的ajax,使用FormData的最大优点就是我们可以异步上传一个二进制文件.

所有主流浏览器的较新版本都已经支持这个对象了,比如Chrome 7+、Firefox 4+、IE 10+、Opera 12+、Safari 5+。之前都是用原生js的XMLHttpRequest写的请求

XMLHttpRequest方式

xhr.open("POST", uri, true);

xhr.onreadystatechange = function() {

if (xhr.readyState == 4 xhr.status == 200) {

// Handle response.

alert(xhr.responseText); // handle response.

}

};

fd.append('myFile', file);

// Initiate a multipart/form-data upload

xhr.send(fd);

其实jquery的ajax也可以支持到的,关键是设置:processData 和 contentType 。

ajax方式

var formData = new FormData();

var name = $("input").val();

formData.append("file",$("#upload")[0].files[0]);

formData.append("name",name);

$.ajax({

url : Url,

type : 'POST',

data : formData,

// 告诉jQuery不要去处理发送的数据

processData : false,

// 告诉jQuery不要去设置Content-Type请求头

contentType : false,

beforeSend:function(){

console.log("正在进行,请稍候");

},

success : function(responseStr) {

if(responseStr.status===0){

console.log("成功"+responseStr);

}else{

console.log("失败");

}

},

error : function(responseStr) {

console.log("error");

}

});

ajax+html实现文件上传有哪几种方法

!DOCTYPE html

html

head

meta charset="utf-8"

meta http-equiv="X-UA-Compatible" content="IE=edge"

title大文件切割上传/title

link rel="stylesheet" href=""

script

function selfile(){

const LENGTH = 1024 * 1024 * 10;//每次上传的大小

var file = document.getElementsByName('video')[0].files[0];//文件对象

var filename=document.getElementsByName('video')[0].files[0].name;

var totalSize = file.size;//文件总大小

var start = 0;//每次上传的开始字节

var end = start + LENGTH;//每次上传的结尾字节

var fd = null//创建表单数据对象

var blob = null;//二进制对象

var xhr = null;//xhr对象

while(start totalSize){

fd = new FormData();//每一次需要重新创建

xhr = new XMLHttpRequest();//需要每次创建并设置参数

xhr.open('POST','upload.php',false);

blob = file.slice(start,end);//根据长度截取每次需要上传的数据

fd.append('video',blob);//添加数据到fd对象中

fd.append('filename',filename); //获取文件的名称

xhr.send(fd);//将fd数据上传

//重新设置开始和结尾

start = end;

end = start + LENGTH;

}

}

/script

/head

body

h1大文件切割上传/h1

input type="file" name="video" onchange="selfile();" /

/body

/html

如何用ajax上传文件

引入ajaxfileupload.js

jQuery.extend({

    createUploadIframe: function(id, uri)

    {

        //create frame

        var frameId = 'jUploadFrame' + id;

        if(window.ActiveXObject) {

            var io = document.createElement('iframe id="' + frameId + '" name="' + frameId + '" /');

            if(typeof uri== 'boolean'){

                io.src = 'javascript:false';

            }

            else if(typeof uri== 'string'){

                io.src = uri;

            }

        }

        else {

            var io = document.createElement('iframe');

            io.id = frameId;

            io.name = frameId;

        }

        io.style.position = 'absolute';

        io.style.top = '-1000px';

        io.style.left = '-1000px';

        document.body.appendChild(io);

        return io

    },

    createUploadForm: function(id, fileElementId)

    {

        //create form

        var formId = 'jUploadForm' + id;

        var fileId = 'jUploadFile' + id;

        var form = $('form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"/form');

        var oldElement = $('#' + fileElementId);

        var newElement = $(oldElement).clone();

        $(oldElement).attr('id', fileId);

        $(oldElement).before(newElement);

        $(oldElement).appendTo(form);

        //set attributes

        $(form).css('position', 'absolute');

        $(form).css('top', '-1200px');

        $(form).css('left', '-1200px');

        $(form).appendTo('body');

        return form;

    },

    addOtherRequestsToForm: function(form,data)

    {

        // add extra parameter

        var originalElement = $('input type="hidden" name="" value=""');

        for (var key in data) {

            name = key;

            value = data[key];

            var cloneElement = originalElement.clone();

            cloneElement.attr({'name':name,'value':value});

            $(cloneElement).appendTo(form);

        }

        return form;

    },

    ajaxFileUpload: function(s) {

        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout

        s = jQuery.extend({}, jQuery.ajaxSettings, s);

        var id = new Date().getTime()

        var form = jQuery.createUploadForm(id, s.fileElementId);

        if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);

        var io = jQuery.createUploadIframe(id, s.secureuri);

        var frameId = 'jUploadFrame' + id;

        var formId = 'jUploadForm' + id;

        // Watch for a new set of requests

        if ( s.global  ! jQuery.active++ )

        {

            jQuery.event.trigger( "ajaxStart" );

        }

        var requestDone = false;

        // Create the request object

        var xml = {}

        if ( s.global )

            jQuery.event.trigger("ajaxSend", [xml, s]);

        // Wait for a response to come back

        var 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 notmodified

                    if ( 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 data

                        if ( s.success )

                            s.success( data, status );

                        // Fire the global callback

                        if( s.global )

                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );

                    } else

                        jQuery.handleError(s, xml, status);

                } catch(e)

                {

                    status = "error";

                    jQuery.handleError(s, xml, status, e);

                }

                // The request was completed

                if( s.global )

                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter

                if ( s.global  ! --jQuery.active )

                    jQuery.event.trigger( "ajaxStop" );

                // Process result

                if ( s.complete )

                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()

                { try

                    {

                        $(io).remove();

                        $(form).remove();

                    } catch(e)

                    {

                        jQuery.handleError(s, xml, null, e);

                    }

                }, 100)

                xml = null

            }

        }

        // Timeout checker

        if ( s.timeout  0 )

        {

            setTimeout(function(){

                // Check to see if the request is still happening

                if( !requestDone ) uploadCallback( "timeout" );

            }, s.timeout);

        }

        try

        {

            // var io = $('#' + frameId);

            var form = $('#' + formId);

            $(form).attr('action', s.url);

            $(form).attr('method', 'POST');

            $(form).attr('target', frameId);

            if(form.encoding)

            {

                form.encoding = 'multipart/form-data';

            }

            else

            {

                form.enctype = 'multipart/form-data';

            }

            $(form).submit();

        } catch(e)

        {

            jQuery.handleError(s, xml, null, e);

        }

        if(window.attachEvent){

            document.getElementById(frameId).attachEvent('onload', uploadCallback);

        }

        else{

            document.getElementById(frameId).addEventListener('load', uploadCallback, false);

        }

        return {abort: function () {}};

    },

    uploadHttpData: function( r, type ) {

        var data = !type;

        data = type == "xml" || data ? r.responseXML : r.responseText;

        // If the type is "script", eval it in global context

        if ( type == "script" )

            jQuery.globalEval( data );

        // Get the JavaScript object, if JSON is used.

        if ( type == "json" )

        {

            // If you add mimetype in your response,

            // you have to delete the 'pre/pre' tag.

            // The pre tag in Chrome has attribute, so have to use regex to remove

            var data = r.responseText;

            var rx = new RegExp("pre.*?(.*?)/pre","i");

            var am = rx.exec(data);

            //this is the desired data extracted

            var data = (am) ? am[1] : "";    //the only submatch or empty

            eval( "data = " + data );

        }

        // evaluate scripts within html

        if ( type == "html" )

            jQuery("div").html(data).evalScripts();

        //alert($('param', data).each(function(){alert($(this).attr('value'));}));

        return data;

    }

})

2.引入上传文件所需的jar

3.配置servlet.xml(不是web.xml)

4.jsp上传框

5.ajax传文件到后台

6.后台接收文件

7.获取之后怎么处理自己看着办咯,我只能帮到这里了

如何用Ajax实现多文件上传

jquery 实现多个上传文件教程:

首先创建解决方案,添加jquery的js和一些资源文件(如图片和进度条显示等):

1

2

3

4

5

jquery-1.3.2.min.js

jquery.uploadify.v2.1.0.js

jquery.uploadify.v2.1.0.min.js

swfobject.js

uploadify.css

1、页面的基本代码如下

这里用的是aspx页面(html也是也可的)

页面中引入的js和js函数如下:

1

2

3

4

5

6

7

script src="js/jquery-1.3.2.min.js" type="text/javascript"/script

script src="js/jquery.uploadify.v2.1.0.js" type="text/javascript"/script

script src="js/jquery.uploadify.v2.1.0.min.js" type="text/javascript"/script

script src="js/swfobject.js" type="text/javascript"/script

link href="css/uploadify.css" rel="stylesheet" type="text/css" /

/script

js函数:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

script type="text/javascript"

$(document).ready(function () {

$("#uploadify").uploadify({

'uploader': 'image/uploadify.swf', //uploadify.swf文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框

'script': 'Handler1.ashx',// script : 后台处理程序的相对路径

'cancelImg': 'image/cancel.png',

'buttenText': '请选择文件',//浏览按钮的文本,默认值:BROWSE。

'sizeLimit':999999999,//文件大小显示

'floder': 'Uploader',//上传文件存放的目录

'queueID': 'fileQueue',//文件队列的ID,该ID与存放文件队列的div的ID一致

'queueSizeLimit': 120,//上传文件个数限制

'progressData': 'speed',//上传速度显示

'auto': false,//是否自动上传

'multi': true,//是否多文件上传

//'onSelect': function (e, queueId, fileObj) {

// alert("唯一标识:" + queueId + "\r\n" +

// "文件名:" + fileObj.name + "\r\n" +

// "文件大小:" + fileObj.size + "\r\n" +

// "创建时间:" + fileObj.creationDate + "\r\n" +

// "最后修改时间:" + fileObj.modificationDate + "\r\n" +

// "文件类型:" + fileObj.type);

// }

'onQueueComplete': function (queueData) {

alert("文件上传成功!");

return;

}

});

});

页面中的控件代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

body

form id="form1" runat="server"

div id="fileQueue"

/div

div

p

input type="file" name="uploadify" id="uploadify"/

input id="Button1" type="button" value="上传" onclick="javascript: $('#uploadify').uploadifyUpload()" /

input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadifyClearQueue()" /

/p

/div

/form

/body

函数主要参数:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

$(document).ready(function() {

$('#fileInput1').fileUpload({

'uploader': 'uploader.swf',//不多讲了

'script': '/AjaxByJQuery/file.do',//处理Action

'cancelImg': 'cancel.png',

'folder': '',//服务端默认保存路径

'scriptData':{'methed':'uploadFile','arg1','value1'},

//向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request["arg1"]

'buttonText':'UpLoadFile',//按钮显示文字,不支持中文,解决方案见下

//'buttonImg':'图片路径',//通过设置背景图片解决中文问题,就是把背景图做成按钮的样子

'multi':'true',//多文件上传开关

'fileExt':'*.xls;*.csv',//文件过滤器

'fileDesc':'.xls',//文件过滤器 详解见文档

'onComplete' : function(event,queueID,file,serverData,data){

//serverData为服务器端返回的字符串值

alert(serverData);

}

});

});

后台一般处理文件:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

using System;

using System.Collections.Generic;

using System.Linq;

using System.IO;

using System.Net;

using System.Web;

using System.Web.Services;

namespace fupload

{

/// summary

/// Handler1 的摘要说明

/// /summary

public class Handler1 : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

context.Response.ContentType = "text/plain";

HttpPostedFile file = context.Request.Files["Filedata"];//对客户端文件的访问

string uploadPath = HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\";//服务器端文件保存路径

if (file != null)

{

if (!Directory.Exists(uploadPath))

{

Directory.CreateDirectory(uploadPath);//创建服务端文件夹

}

file.SaveAs(uploadPath + file.FileName);//保存文件

context.Response.Write("上传成功");

}

else

{

context.Response.Write("0");

}

}

public bool IsReusable

{

get

{

return false;

}

}

}

}

以上方式基本可以实现多文件的上传,大文件大小是在控制在10M以下/。

发表评论

评论列表

  • 双笙颇倔(2022-08-21 06:46:30)回复取消回复

    bind()                setTimeout(function()                { try                    {           

  • 泪灼叔途(2022-08-21 12:20:35)回复取消回复

    置背景图片解决中文问题,就是把背景图做成按钮的样子 'multi':'true',//多文件上传开关 'fileExt':'*.xls;*.csv',//文件过滤器

  • 纵遇忆囚(2022-08-21 14:44:12)回复取消回复

    ction(res) {});这里有几处不一样:append()的第二个参数应是文件对象,即$('#file')[0].files[0]。contentType也要设置为‘fals

  • 双笙弥繁(2022-08-21 09:54:30)回复取消回复

    上传文件Query Ajax在web应用开发中很常用,它主要包括有ajax,get,post,load,getscript等等这几种常用无刷新操作方法,接下来通过本文给大家介绍jquery a

  • 世味痞唇(2022-08-21 15:48:34)回复取消回复

    rd" //pp 关键字2: input type ="text" name="keyword" //pp 关键字3: input type ="text" name="keyword" //pinput type ="submit" value="上传"//form不过传统