Jquery_异步上传文件多种方式归纳

1.不用任何插件,利用iframe,将form的taget设为iframe的name,注意设为iframe的id是没用的,跟网上很多说的不太一致

iframe_upload.htm

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <form id="form1" method="post" action="Upload.aspx" enctype="multipart/form-data" target="uploadframe">
        <input type="file" id="upload" name="upload" />
        <input type="submit" value="Upload" />
    </form>
    <iframe id="uploadframe" name="uploadframe" style="visibility:hidden"></iframe>
</body>
</html>
Upload.aspx

<%@ Page Language="C#" %>
<%
    Response.ClearContent();
    try
    {
        if (Request.Files.Count == 0) Response.Write("Error");
        else
        {
            HttpPostedFile file= Request.Files[0];

            string ext = System.IO.Path.GetExtension(file.FileName);
            string folder = HttpContext.Current.Server.MapPath("~\\Upload\\");
            string path = folder + Guid.NewGuid().ToString() + ext;
            file.SaveAs(path);
            
            Response.Write("Success");
        }
    }
    catch
    {
        Response.Write("Error");
    }
%>

2.利用ajaxupload.js

Default.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>Ajax Upload Demo</title>
        <script type="text/javascript" src="Scirpt/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="Scirpt/ajaxupload.js"></script>
        <script type="text/javascript">
            $(function ()
            {
                // 创建一个上传参数
                var uploadOption =
                {
                    // 提交目标
                    action: "Upload.aspx",
                    // 自动提交
                    autoSubmit: false,
                    // 选择文件之后…
                    onChange: function (file, extension) {
                        if (new RegExp(/(jpg)|(jpeg)|(bmp)|(gif)|(png)/i).test(extension)) {
                            $("#filepath").val(file);
                        } else {
                            alert("只限上传图片文件,请重新选择!");
                        }
                    },
                    // 开始上传文件
                    onSubmit: function (file, extension) {
                        $("#state").val("正在上传" + file + "..");
                    },
                    // 上传完成之后
                    onComplete: function (file, response) {
                        if (response == "Success") $("#state").val("上传完成!");
                        else $("#state").val(response);
                    }
                }

                // 初始化图片上传框
                var oAjaxUpload = new AjaxUpload(#selector, uploadOption);

                // 给上传按钮增加上传动作
                $("#up").click(function ()
                {
                    oAjaxUpload.submit();
                });
            });
        </script>
    </head>
    <body>
        <div>
            <label>一个普通的按钮:</label><input type="button" value="选取图片" id="selector" />
            <br />
            <label>选择的图片路径:</label><input type="text" readonly="readonly" value="" id="filepath" />
            <br />
            <label>不是submit按钮:</label><input type="button" value="上传" id="up" />
            <br />
            <label>上传状态和结果:</label><input type="text" readonly="readonly" value="" id="state" />
        </div>
    </body>
</html>
Upload.aspx

<%@ Page Language="C#" %>
<%
    Response.ClearContent();
    try
    {
        if (Request.Files.Count == 0) Response.Write("Error");
        else
        {
            HttpPostedFile file= Request.Files[0];

            string ext = System.IO.Path.GetExtension(file.FileName);
            string folder = HttpContext.Current.Server.MapPath("~\\Upload\\");
            string path = folder + Guid.NewGuid().ToString() + ext;
            file.SaveAs(path);
            
            Response.Write("Success");
        }
    }
    catch
    {
        Response.Write("Error");
    }
%>

3.利用ajaxfileupload.html

ajaxfileupload.html

<html>
<head>
    <title>Ajax File Uploader Plugin For Jquery</title>
    <script src="Scirpt/jquery.js" type="text/javascript"></script>
    <script src="Scirpt/ajaxfileupload.js" type="text/javascript"></script>
    <script type="text/javascript">
        function ajaxFileUpload() {
            $("#loading")
        .ajaxStart(function () {
            $(this).show();
        })
        .ajaxComplete(function () {
            $(this).hide();
        });

            $.ajaxFileUpload
            (
                {
                    url: Upload3.aspx,
                    secureuri: false,
                    fileElementId: fileToUpload,
                    dataType: json,
                    data: { name: logan, id: id },
                    success: function (data, status) {
                        if (typeof (data.error) != undefined) {
                            if (data.error != ‘‘) {
                                alert(data.error);
                                //alert(data.error.toJSONString());
                            } else {
                                alert(data.msg);
                                //alert(data.toJSONString());
                            }
                        }
                    },
                    error: function (data, status, e) {
                        //alert(e.toJSONString());
                        alert(e);
                    }
                }
            )

            return false;

        }
    </script>
</head>
<body>
    <div id="wrapper">
        <div id="content">
            <h1>
                Ajax File Upload Demo</h1>
            <img id="loading" src="loading.gif" style="display: none;">
            <form name="form" action="" method="post" enctype="multipart/form-data">
            <table cellpadding="0" cellspacing="0" class="tableForm">
                <thead>
                    <tr>
                        <th>
                            Please select a file and click Upload button
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            <input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input" />
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td>
                            <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">
                                Upload</button>
                        </td>
                    </tr>
                </tfoot>
            </table>
            </form>
        </div>
</body>
</html>
Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Upload
{
    public partial class Upload3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (null == files || files.Count == 0)
            {
                //DoNothing
            }
            else
            {
                string msg = null;
                msg = UploadMain();
                //Response.ContentType = "application/json";
                Response.Write(msg);
                Response.End();
            }
        }

        private string UploadMain()
        {
            HttpPostedFile file = Request.Files[0];

            string ext = System.IO.Path.GetExtension(file.FileName);
            string folder = HttpContext.Current.Server.MapPath("~\\Upload\\");
            string fileName = Guid.NewGuid().ToString() + ext;
            string path = folder + fileName;
            file.SaveAs(path);


            string message = getMsg("0047 File Upload Success!", null);

            return message;
        }

        private string getMsg(string msg, string err)
        {
            if (String.IsNullOrEmpty(msg))
            {
                msg = "";
            }
            if (String.IsNullOrEmpty(err))
            {
                err = "";
            }

            string message = "{";
            message += "msg:‘#msg#‘,";
            message += "error:‘#err#‘";
            message += "}";

            return message.Replace("#msg#", msg).Replace("#err#", err);

        }
    }
}

4.html5+html5uploader.js

html5uploder.htm

<!DOCTYPE html>
<html>
<script src="Scirpt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="Scirpt/jquery.html5uploader.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $("#multiple").html5Uploader({
            postUrl: "Upload2.aspx",
            onSuccess: function (a, b, c) {
                var img = $(<img/>).attr(src, "http://localhost:83/Upload/"+c).css(width, 140px).css(height, 140px).css(margin, 10px);
                $(#content).append(img);
            }
        });
    });
</script>
<head>
    <title></title>
</head>
<body>
    <input id="multiple" type="file" accept="image/*"  multiple />
    <div id="content"></div>
</body>
</html>
Default2.aspx

<%@ Page Language="C#" %>
<%
    Response.ClearContent();
    try
    {
        if (Request.Files.Count == 0) Response.Write("Error");
        else
        {
            HttpPostedFile file= Request.Files[0];

            string ext = System.IO.Path.GetExtension(file.FileName);
            string folder = HttpContext.Current.Server.MapPath("~\\Upload\\");
            string fileName = Guid.NewGuid().ToString()+ext;
            string path = folder + fileName;
            file.SaveAs(path);

            Response.Write(fileName);
        }
    }
    catch
    {
        Response.Write("Error");
    }
%>

Jquery_异步上传文件多种方式归纳,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。