异步上传文件

摘要:
异步上传文件多种方式归纳最近在做异步上传文件的工作,用到了一些库,这里归纳下,暂且不考虑异常处理,仅作为demo。DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"˃AjaxUploadDemo$(function(){//创建一个上传参数varuploadOption={//提交目标action:"Upload.aspx",//自动提交autoSubmit:false,//选择文件之后…onChange:function{if{$.val;}else{alert("只限上传图片文件,请重新选择!
异步上传文件多种方式归纳

最近在做异步上传文件的工作,用到了一些库,这里归纳下,暂且不考虑异常处理,仅作为demo。

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   method="post" action="Upload.aspx" enctype="multipart/form-data" target="uploadframe">
        <input type="file"   name="upload" />
        <input type="submit" value="Upload" />
    </form>
    <iframe   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="http://t.zoukankan.com/Scirpt/jquery-1.10.2.min.js"></script>
        <script type="text/javascript" src="http://t.zoukankan.com/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="选取图片"   />
            <br />
            <label>选择的图片路径:</label><input type="text" readonly="readonly" value=""   />
            <br />
            <label>不是submit按钮:</label><input type="button" value="上传"   />
            <br />
            <label>上传状态和结果:</label><input type="text" readonly="readonly" value=""   />
        </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="http://t.zoukankan.com/Scirpt/jquery.js" type="text/javascript"></script>
    <script src="http://t.zoukankan.com/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   src="http://t.zoukankan.com/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   type="file" size="45" name="fileToUpload"   />
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td>
                            <button     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="http://t.zoukankan.com/Scirpt/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="http://t.zoukankan.com/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   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");
    }
%>
复制代码

免责声明:文章转载自《异步上传文件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇【转】Hbuilder配置Avalon、Vue指令提示通配符的匹配很全面, 但无法找到元素 'context:component-scan' 的声明下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

数据持久化之sqlite基本用法

一、ACID 即原子性(Atomicity)、一致性(Consistency)、隔离性(Isolation)、持久性(Durability)。 原子性:整个事务中的所有操作,要么全部完成,要么全部不完成,不可能停滞在中间某个环节。 一致性:事务在完成时,必须使所有的数据都保持一致状态。 隔离性:隔离状态执行事务,使它们好像是系统在给定时间内执行的唯一操作。...

kaptcha Java验证码

原文:http://www.cnblogs.com/chizizhixin/p/5311619.html 在项目中经常会使用验证码,kaptcha 就一个非常不错的开源框架,分享下自己在项目中的使用: 1、首先下载kaptcha 把kaptcha-2.3.2.jar包放在lib下 2、登陆页面初始化 document.getElementById("myc...

[Google Guava]学习--新集合类型Multimap

每个有经验的Java程序员都在某处实现过Map<K, List<V>>或Map<K, Set<V>>,并且要忍受这个结构的笨拙。 假如目前有个需求是给两个年级添加5个学生,并且统计出一年级学生的信息: public classMultimapTest { classStudent {...

asp.net core系列 31 EF管理数据库架构--必备知识 反向工程

一.   反向工程   反向工程是基于数据库架构,生成的实体类和DbContext类代码的过程,对于Visual Studio开发,建议使用PMC。对于其他开发环境,请选择.NET Core CLI工具(跨平台)。     (1) 在程序包管理器控制台(PMC)工具中使用命令Scaffold-DbContext 来进行反向工程。     (2) 在.NET...

【C#】WebApi 添加过滤器,实现对请求参数和响应内容的日志记录

filter的介绍 filter在Web API中经常会用到,主要用于记录日志,安全验证,全局错误处理等;Web API提供两种过滤器的基本类型:actionfilterattribute,exceptionfilterattribute;两个类都是抽象类,actionfilter主要实现执行请求方法体之前(覆盖基类方法OnActionExecuting...

C#文件处理相关内容

C#修改文件内容和过滤有效内容,文件格式一定。 OpenFileDialog file = new OpenFileDialog();//定义新的文件打开位置控件 file.InitialDirectory =Application.StartupPath; file.Filter...