使现代化

我能够让一切正常工作,我只是想发回更新后的代码.我使用了Darin Dimitrov的建议,即使用一个单独的通用http处理程序来处理文件上载,所以这是我为此而编写的代码...如果你有问题,请告诉我.

<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Web;

public class Upload : IHttpHandler {

    public void ProcessRequest(HttpContext context) {

        /**
         * If 'newTicket' is "false", then the directory to upload to already exists and we can extract it from
         * the 'ticketID' POST parameter.
         * 
         * If 'newTicket' is "true", then this is a new Ticket submission so we need to work with a NEW directory 
         * on the server, so the ID needs to be 1 more than the total number of directories in ~/TicketUploads/
         */
        String newTicket = context.Request["newTicket"] != null ? context.Request["newTicket"] : String.Empty;
        int theID = -1;
        if (newTicket.Equals("true")) {

            // we need to calculate a new ID
            theID = getNewID(context); // calculate the new ID = # of rows
            theID++; // add 1 to make it unique
        } else if (newTicket.Equals("false")) {

            // we can just get the ID from the POST parameter
            theID = context.Request["ticketID"] != null ? Convert.ToInt32(context.Request["ticketID"]) : -1;
        } else {

            // something went wrong with the 'newTicket' POST parameter
            context.Response.ContentType = "text/plain";
            context.Response.Write("Error with 'newTicket' POST parameter.");
        }

        // if theID is negative, something went wrong... can't continue
        if (theID < 0) {
            return;
        }

        // ready to read the files being uploaded and upload them to the correct directory
        int chunk = context.Request["chunk"] != null ? int.Parse(context.Request["chunk"]) : 0;
        string fileName = context.Request["name"] != null ? context.Request["name"] : string.Empty;
        var uploadPath = context.Server.MapPath("~/TicketUploads/" + theID + "/");
        HttpPostedFile fileUpload = context.Request.Files[0];

        // if the NEW directory doesn't exist, create it
        DirectoryInfo di = new DirectoryInfo("" + uploadPath + "");
        if (!(di.Exists)) {
            di.Create();
        }

        using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append)) {
            var buffer = new byte[fileUpload.InputStream.Length];
            fileUpload.InputStream.Read(buffer, 0, buffer.Length);
            fs.Write(buffer, 0, buffer.Length);
        }

        context.Response.ContentType = "text/plain";
        context.Response.Write("File uploaded.");
        return;
    }
}

我正在try 在ASP中集成Plupload文件上传程序.NET使用C#.我读过Angry Monkeys articleMarco Valsecchi blog post,但我有点迷路了.

上述文章提出的C#大致类似于以下内容:

int chunk = Request.QueryString["chunk"] != null ? int.Parse(Request.QueryString["chunk"]) : 0;
string fileName = Request.QueryString["name"] != null ? Request.QueryString["name"] : string.Empty;

HttpPostedFile fileUpload = Request.Files[0];

using (FileStream fs = new FileStream(Server.MapPath("~/TicketUploads/" + fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
{
    Byte[] buffer = new Byte[fileUpload.InputStream.Length];
    fileUpload.InputStream.Read(buffer, 0, buffer.Length);

    fs.Write(buffer, 0, buffer.Length);
    fs.Close();
}

首先,我已经设置了Plupload配置,如下所示:

$("#plupload_container").pluploadQueue({
  runtimes: 'html5,gears,flash,silverlight,html4',
  flash_swf_url: '../plupload/js/plupload.flash.swf',
  silverlight_xap_url: '../plupload/js/plupload.silverlight.xap',
  filters: [
    { title: "Image files", extensions: "jpg,gif" },
    { title: "Zip files", extensions: "zip" },
    { title: "Document files", extensions: "doc,pdf,txt" }
  ]
});

... 但我觉得我错过了一些上传工作所必需的东西.

我想我的主要问题是如何调用上面的C#代码以便开始上传?我在一个名为SubmitRequest.aspx的页面上有一张表格.单击表单上的"提交"将产生以下结果:

$('form').submit(function (e) {

  // Validate number of uploaded files
  if (uploader.total.uploaded == 0) {
    // Files in queue upload them first
    if (uploader.files.length > 0) {
      // When all files are uploaded submit form
      uploader.bind('UploadProgress', function () {
        if (uploader.total.uploaded == uploader.files.length)
          $('form').submit();
      });
      uploader.start();
    }
    e.preventDefault();
  }
});

...因此,当单击"提交"时,上传程序启动并上传文件.一旦完成,表单的睡觉就会提交.我不明白如何将此事件链接到将处理上传到服务器上的文件夹TicketUploads的C#代码.

我为这篇较长的帖子道歉,但如果有任何帮助,我将不胜感激:)

推荐答案

下面是我为大家写的一个完整的工作示例:

<%@ Page Title="Home Page" Language="C#" %>
<%@ Import Namespace="System.IO" %>
<script runat="server" type="text/c#">
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check to see whether there are uploaded files to process them
        if (Request.Files.Count > 0)
        {
            int chunk = Request["chunk"] != null ? int.Parse(Request["chunk"]) : 0;
            string fileName = Request["name"] != null ? Request["name"] : string.Empty;

            HttpPostedFile fileUpload = Request.Files[0];

            var uploadPath = Server.MapPath("~/TicketUploads");
            using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
            {
                var buffer = new byte[fileUpload.InputStream.Length];
                fileUpload.InputStream.Read(buffer, 0, buffer.Length);

                fs.Write(buffer, 0, buffer.Length);
            }
        }
    }
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>

    <style type="text/css">@import url(css/plupload.queue.css);</style>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("jquery", "1.3");
    </script>
    <script type="text/javascript" src="/plupload/js/gears_init.js"></script>
    <script type="text/javascript" src="http://bp.yahooapis.com/2.4.21/browserplus-min.js"></script>
    <script type="text/javascript" src="/plupload/js/plupload.full.min.js"></script>
    <script type="text/javascript" src="/plupload/js/jquery.plupload.queue.min.js"></script>
    <script type="text/javascript">
    $(function() {
        $("#uploader").pluploadQueue({
            // General settings
            runtimes : 'gears,flash,silverlight,browserplus,html5',
            url : '/default.aspx',
            max_file_size : '10mb',
            chunk_size : '1mb',
            unique_names : true,
            // Resize images on clientside if we can
            resize : {width : 320, height : 240, quality : 90},
            // Specify what files to browse for
            filters : [
                {title : "Image files", extensions : "jpg,gif,png"},
                {title : "Zip files", extensions : "zip"}
            ],
            // Flash settings
            flash_swf_url : '/plupload/js/plupload.flash.swf',
            // Silverlight settings
            silverlight_xap_url : '/plupload/js/plupload.silverlight.xap'
        });

        // Client side form validation
        $('form').submit(function(e) {
            var uploader = $('#uploader').pluploadQueue();
            // Validate number of uploaded files
            if (uploader.total.uploaded == 0) {
                // Files in queue upload them first
                if (uploader.files.length > 0) {
                    // When all files are uploaded submit form
                    uploader.bind('UploadProgress', function() {
                        if (uploader.total.uploaded == uploader.files.length)
                            $('form').submit();
                    });
                    uploader.start();
                } else
                    alert('You must at least upload one file.');
                e.preventDefault();
            }
        });
    });
    </script>

</head>
<body>
    <form id="Form1" runat="server">
        <div id="uploader">
            <p>You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
        </div>
    </form>
</body>
</html>

正如您将在本例中看到的,文件被上载到名为default.aspx的同一个页面.注意,像chunkname这样的参数是发布的,所以您不应该使用Request.QueryString来读取它们,而应该直接使用Request["chunk"]来读取它们,因为这也会查看POST正文.您还应该确保服务器上的根目录下存在TicketUploads文件夹.

在本例中,同一页default.aspx用于显示上载表单和处理上载.在真实的应用程序中,这不是我会做的事情.我建议您使用单独的脚本来处理文件上传,比如通用的http处理程序(pload.ashx).

最后,您会注意到我使用了一些默认设置,您可能希望修改和重新配置插件以满足您的需要.我刚从文档中获取了设置.


更新:

由于我建议使用一个单独的通用http处理程序来处理文件上传,下面是它的外观:

using System.IO;
using System.Web;

public class Upload : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        int chunk = context.Request["chunk"] != null ? int.Parse(context.Request["chunk"]) : 0;
        string fileName = context.Request["name"] != null ? context.Request["name"] : string.Empty;

        HttpPostedFile fileUpload = context.Request.Files[0];

        var uploadPath = context.Server.MapPath("~/TicketUploads");
        using (var fs = new FileStream(Path.Combine(uploadPath, fileName), chunk == 0 ? FileMode.Create : FileMode.Append))
        {
            var buffer = new byte[fileUpload.InputStream.Length];
            fileUpload.InputStream.Read(buffer, 0, buffer.Length);

            fs.Write(buffer, 0, buffer.Length);
        }

        context.Response.ContentType = "text/plain";
        context.Response.Write("Success");
    }

    public bool IsReusable
    {
        get { return false; }
    }
}

现在只需重新配置插件,使其指向以下通用处理程序:

...
runtimes: 'gears,flash,silverlight,browserplus,html5',
url: '/upload.ashx',
max_file_size: '10mb',
...

Asp.net相关问答推荐

更新剃须刀页面中图表的值

如何根据另一个下拉列表中的 Select 从下拉列表中删除一个值?

如何在asp.net中单击按钮的新选项卡中打开页面?

从 Request.Url.AbsolutePath 获取应用相对 url

/应用程序中的服务器错误. ASP.NET

ASP.NET Membership:如何将用户设置为已登录

如何在不使用 Session 的情况下在 ASP.net 中的页面之间传递值

ASP.Net Core MVC - 自定义属性的客户端验证

LINQ to Entities 无法识别 MVC 4 中的System.String ToString()方法

如何从 Asp.net Mvc-3 发送邮箱?

使用 LINQ 进行递归控制搜索

您使用哪个 .NET Memcached 客户端,EnyimMemcached 与 BeITMemcached?

在 Visual Studio 2010 Professional 中找不到请求的 .Net Framework 数据提供程序

Web.Config 中的 Assemblies node 的用途是什么?

如何将表从存储过程检索到数据表?

如何将参数传递给 ASP.NET MVC 2 中的自定义 ActionFilter?

简单的 LINQ 和列表错误:WhereListIterator`1[Task]' to type 'System.Collections.Generic.List`1[Task]'

如何从 ASP.NET Identity 获取用户列表?

中继器中的中继器

在 ASP.NET 中写入文件以响应后回发不起作用