Uploadify 3.2上传文件,限制类型,大小,传递参数等

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="upload.aspx.cs" Inherits="PDF2016.upload" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>uploadify3.2上传文件</title>
    <script src="js/jquery-1.10.2.min.js"></script>
    <link href="js/uploadify3.2/uploadify.css" rel="stylesheet" />
    <script src="js/uploadify3.2/jquery.uploadify.min.js"></script>
    <script type="text/javascript">
        $(function () {
            /*************setting***************/
            var definedData = [];
            definedData.auth = "@(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)";
            definedData.ASPSESSID = "@Session.SessionID";
            definedData.fileTypeExts = "*.doc;*.docx;*.xls;*.xlsx;*.pdf;*.ppt;*.txt;*.rar;*.zip;*.exe";    //上传类型
            definedData.uploader = "/UploadHandler.ashx";    //后台处理路径
            definedData.fileSizeLimit = "2MB";  //上传大小
            definedData.fileObjName = "file_upload";    //控件名
            definedData.queueSizeLimit = 1;      //允许上传个数文件
            var data = { 'ASPSESSID': definedData.ASPSESSID, 'AUTHID': definedData.auth };    //firefox用swf上传丢失session

            var errorData = [];
            errorData.err100 = "文件个数超出系统限制,只允许上传" + definedData.queueSizeLimit + "个文件!";
            errorData.err110 = "文件超出系统限制的大小,限制文件大小" + definedData.fileSizeLimit + "!";
            errorData.err120 = "文件大小异常!";
            errorData.err130 = "文件类型不正确,只允许上传后缀名" + definedData.fileTypeExts + "!";
            /*************setting***************/
            $("#file_upload").uploadify({
                'buttonText': '选择资源',
                'swf': '/js/uploadify3.2/uploadify.swf',
                'uploader': definedData.uploader,
                'auto': false, //当文件被添加到队列时,自动上传
                'formData': data, //上传时传递数据
                'fileObjName': definedData.fileObjName,
                'queueSizeLimit': definedData.queueSizeLimit,
                'fileTypeExts': definedData.fileTypeExts,
                'fileSizeLimit': definedData.fileSizeLimit,
                'onUploadSuccess': function(file, data, response) {
                    $('#file_upload').uploadify('cancel', '*'); //隐藏进度条</span>
                    var dataJson = JSON.parse(data);
                    if (dataJson.Status) {
                        //上传成功
                        alert(dataJson.Message);
                    } else {
                        //上传失败
                        alert(dataJson.Message);
                    }
                },
                //返回一个错误,选择文件的时候触发
                'onSelectError': function (file, errorCode, errorMsg) {
                    switch (errorCode) {
                        case -100:
                            alert(errorData.err100);
                            break;
                        case -110:
                            alert(errorData.err110);
                            break;
                        case -120:
                            alert(errorData.err120);
                            break;
                        case -130:
                            alert(errorData.err130);
                            break;
                    }
                },
                //检测FLASH失败调用  
                'onFallback': function () {
                    alert("您未安装FLASH控件,无法上传!请安装FLASH控件后再试。");
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <p><input type="file" name="file_upload" id="file_upload" /></p>
            <p>
                <img src="js/uploadify3.2/upload.jpg" style="cursor: pointer;" onclick="javascript:$('#file_upload').uploadify('upload')" />
            </p>
        </div>
    </form>
</body>
</html>

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Newtonsoft.Json;

namespace PDF2016
{
    /// <summary>
    /// UploadHandler 的摘要说明
    /// </summary>
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            UploadResult result = new UploadResult();
            HttpPostedFile file = context.Request.Files["file_upload"];
            string folder = context.Server.MapPath("~/upload/");
            if (file != null && file.ContentLength > 0)
            {
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }
                file.SaveAs(Path.Combine(folder, file.FileName));
                result.Status = true;
                result.Message =  file.FileName;
            }
            else
            {
                result.Status = false;
                result.Message = "请选择上传文件";
            }
            string json = JsonConvert.SerializeObject(result, Formatting.Indented);
            context.Response.Write(json);
        }


        public class UploadResult
        {
            public bool Status;
            public string Message;
        }

        public bool IsReusable
        {
            get { return false; }
        }
    }
}
//在Global.asax中添加如下代码
//using System.Web.Security;
protected void Application_BeginRequest(object sender, EventArgs e)
{
	try
	{
		string session_param_name = "ASPSESSID";
		string session_cookie_name = "ASP.NET_SESSIONID";

		if (HttpContext.Current.Request.Form[session_param_name] != null)
		{
			UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
		}
		else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
		{
			UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
		}
	}
	catch (Exception)
	{
	}

	try
	{
		string auth_param_name = "AUTHID";
		string auth_cookie_name = FormsAuthentication.FormsCookieName;

		if (HttpContext.Current.Request.Form[auth_param_name] != null)
		{
			UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
		}
		else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
		{
			UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
		}

	}
	catch (Exception)
	{
	}


}
void UpdateCookie(string cookie_name, string cookie_value)
{
	HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
	if (cookie == null)
	{
		HttpCookie cookie1 = new HttpCookie(cookie_name, cookie_value);
		Response.Cookies.Add(cookie1);
	}
	else
	{
		cookie.Value = cookie_value;
		HttpContext.Current.Request.Cookies.Set(cookie);
	}
}


posted @ 2016-07-08 17:27  深南大道  阅读(164)  评论(0编辑  收藏  举报