using Plupload with ASP.NET/C#

后端 未结 2 1521
Happy的楠姐
Happy的楠姐 2020-12-07 11:15

UPDATE

I was able to get everything to work properly and I just wanted to post back with the updated code. I used Darin Dimitrov\'s suggestion on using a separate

相关标签:
2条回答
  • 2020-12-07 11:48

    Here is a VB example of an ashx file for pluploader.

    Thanks to @@Darin Dimitrov Who suggested this. Its the best solution ever with many fall backs like silverlight,flash.. etc.. its mega!

    I did not find any VB examples so i converted it my self- tested and works! With chunking!

    To add a ashx file to your website in VisualStudio. Right click the website

    website > add new item > generic handler

    This is all in one page no need for code behind. Just call this from the pluplaod plugin

    <%@ WebHandler Language="VB" Class="upload" %>
    
    Imports System
    Imports System.IO
    Imports System.Web
    
    
    Public Class upload : Implements IHttpHandler
    
    
        Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            Dim chunk As Integer = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
            Dim fileName As String = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
    
            Dim fileUpload As HttpPostedFile = context.Request.Files(0)
    
            Dim uploadPath = context.Server.MapPath("~/uploads")
            Using fs = New FileStream(Path.Combine(uploadPath, fileName), If(chunk = 0, FileMode.Create, FileMode.Append))
                Dim buffer = New Byte(fileUpload.InputStream.Length - 1) {}
                fileUpload.InputStream.Read(buffer, 0, buffer.Length)
    
                fs.Write(buffer, 0, buffer.Length)
            End Using
    
            context.Response.ContentType = "text/plain"
            context.Response.Write("Success")
        End Sub
    
        Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                Return False
            End Get
        End Property
    
    End Class
    
    0 讨论(0)
  • 2020-12-07 12:06

    Here's a full working example I wrote for you:

    <%@ 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>
    

    As you will see in this example files are uploaded to the same page called default.aspx. Notice that parameters such as chunk and name are POSTed so you shouldn't use Request.QueryString to read them but Request["chunk"] directly as this will look at the POST body as well. You should also make sure that the TicketUploads folder exists on the server at the root.

    In this example the same page default.aspx is used for showing the upload form and handling the uploads. In a real world application this is not something I would do. I would recommend you using a separate script which will handle the file uploads such as a generic http handler (upload.ashx).

    Finally you will notice that I have used some default settings that you might wish to modify and reconfigure the plugin to fit your needs. I just took the settings from the documentation.


    UPDATE:

    And since I recommended using a separate generic http handler for handling the file uploads here's how it might look :

    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; }
        }
    }
    

    Now all that's left is to reconfigure the plugin to point to this generic handler:

    ...
    runtimes: 'gears,flash,silverlight,browserplus,html5',
    url: '/upload.ashx',
    max_file_size: '10mb',
    ...
    
    0 讨论(0)
提交回复
热议问题