4

我在 ASP.NET(不是 MVC)项目的 aspx 页面中的标记中有以下 Fine Uploader 代码:

<link href="../js/fineuploader/fineuploader-3.5.0.css" rel="stylesheet">
<script type="text/javascript" src="../js/fineuploader/fineuploader-3.5.0.js"></script>
<script type="text/javascript">
   $(document).ready(function () {
      var uploader = new qq.FineUploader({
         element: $('#fine-uploader')[0],
         request: {  /* <-- THIS IS WHAT I NEED TO FIGURE OUT */
            endpoint: 'server/handleUploads'
         },
         autoUpload: true,
         multiple: false,
         text: {
            uploadButton: '<asp:Button ID="fineUploadButton" runat="server" CssClass="button" style="width:6;5" Text="Browse" />'
         },
         validation: {
            allowedExtensions: ['mp3', 'wav']
         }
      });
   });
</script>

对于客户端部分,这很好用。我已经修改了fineuploader.css 以获得我想要的确切外观(大部分)。随着客户端部分的完成,我只需要在我的代码隐藏中处理这个request endpoint部分。

我在 github 页面上查看了几个示例,但对于 ASP,没有非 MVC 示例。即使是这些示例中最简单的示例,也涉及创建一个新类并从该类继承Controller。由于我没有使用 MVC 做这个站点,我该如何处理服务器端方面的问题?

我的客户端部分非常完整,如有必要,我可以提供有关我的服务器端代码和组织的更多信息。

4

3 回答 3

4

处理 Fine Uploader 发送的请求相当简单。默认情况下,所有上传请求都是多部分编码的 POST 请求。默认情况下,所有参数也作为表单字段存在于请求负载中。

我不是 ASP.NET 开发人员,但在 ASP.NET 中处理 MPE 请求应该不会太难。事实上,这在大多数服务器端语言中是相当微不足道的。下面是一些应该处理此类请求的代码示例:

using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

}

请注意,您的服务器端代码还必须返回有效的 JSON 响应。这在Fine Uploader 的服务器端自述文件中有更多描述。MSDN 上有一篇文章描述了在 .NET 应用程序中处理 JSON。也许JsonConvert这里需要这个类。

您可以在http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2阅读有关处理这些请求的更多信息。

于 2013-05-23T15:13:57.537 回答
1

Kmarks2,对您来说可能为时已晚,但这可以帮助其他人。

为了在 ASP.NET(不是 MVC)中处理它的服务器端,可以创建一个 WebHandler。它是带有 .ashx 扩展名的通用处理程序项(例如 FileUpload.ashx )。

处理程序如下所示:

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

using System;
using System.Web;
using System.IO;

public class FileUpload : IHttpHandler {

public void ProcessRequest (HttpContext context) 
{
  // Handle files sent from client
}

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

端点应如下所示:'http://你的服务器名称/xxx/FileUpload.ashx'(例如' http://localhost:3293/xxx/FileUpload.ashx ')

于 2017-05-26T16:32:57.440 回答
0

使用不是 MVC 项目的 ASP.NET需要WebHandler来无缝处理请求。有关 WebHandler 的示例和用法,请参见此处

参考SanthoshM的答案并结合 Fine Uploader MVC VB.net Server-Side 示例,这就是我想出的。我希望这可能对某人有所帮助。

客户端

<script> 
           var existingHandler1 = window.onload;
           window.document.body.onload = function () {
               var galleryUploader = new qq.FineUploader({
                   element: document.getElementById("fine-uploader-gallery"),
                   template: 'qq-template-gallery',
                   request: {
                       endpoint: '../App_Extension/FileUpload.ashx'
                   },
                   debug: true,
                   thumbnails: {
                       placeholders: {
                           waitingPath: '../App_Images/waiting-generic.png',
                           notAvailablePath: '../App_Images/not_available-generic.png'
                       }
                   },
                   validation: {
                       allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
                       sizeLimit: 3145728 // 3 MB = 3 * 1024 * 1024 bytes
                   },
                   retry: {
                       enableAuto: true
                   },
               });
               if (existingHandler1) { existingHandler1() }
           }

    </script>

服务器端

<%@ WebHandler Language="VB" Class="FileUpload" %>

Imports System
Imports System.Web
Imports System.IO
Imports System.Linq
Imports System.Drawing


Public Class FileUpload : Implements IHttpHandler

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        context.Response.ContentType = "text/plain"
        'context.Response.Write("Hello World")
        Dim reader As StreamReader = New StreamReader(context.Request.InputStream)
        Try
            Dim values As String = DateTime.Now.Millisecond.ToString + Rnd(10000).ToString + ".jpg" 'reader.ReadToEnd()
            ' 'BLL.WriteLog(values)
            'Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(context.Request.InputStream)
            ' img.Save("C:\DownloadedFiles\" + DateAndTime.TimeString + ".Jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
            ''BLL.WriteLog(values)
            Dim responseText As String = Upload(values, context)
            'BLL.WriteLog(responseText)
            context.Response.Write(responseText)
            'context.Response.Write("{""error"":""An Error Occured""}")
        Catch ex As Exception
            'BLL.WriteLog(ex.Message + ex.StackTrace)
        End Try
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property



    Function Upload(ByVal uploadFile As String, ByVal context As HttpContext) As String
        'BLL.WriteLog("1")
        On Error GoTo upload_error
        Dim strm As Stream = context.Request.InputStream
        Dim br As BinaryReader = New BinaryReader(strm)
        Dim fileContents() As Byte = {}
        Const ChunkSize As Integer = 1024 * 1024
        'Dim uploadFile As String

        'BLL.WriteLog("2")
        ' We need to hand IE a little bit differently...
        ' If context.Request.Browser.Browser = "IE" Then

        'BLL.WriteLog("3")
        Dim myfiles As System.Web.HttpFileCollection = System.Web.HttpContext.Current.Request.Files
        Dim postedFile As System.Web.HttpPostedFile = myfiles(0)
        If Not postedFile.FileName.Equals("") Then
            Dim fn As String = System.IO.Path.GetFileName(postedFile.FileName)
            br = New BinaryReader(postedFile.InputStream)
            uploadFile = fn
        End If
        'End If

        'BLL.WriteLog("4")
        ' Nor have the binary reader on the IE file input Stream. Back to normal...
        Do While br.BaseStream.Position < br.BaseStream.Length - 1
            'BLL.WriteLog("5")
            Dim b(ChunkSize - 1) As Byte
            Dim ReadLen As Integer = br.Read(b, 0, ChunkSize)
            Dim dummy() As Byte = fileContents.Concat(b).ToArray()
            fileContents = dummy
            dummy = Nothing
        Loop

        'BLL.WriteLog("6")

        ' You now have all the bytes from the uploaded file in 'FileContents'

        ' You could write it to a database:

        'Dim con As SqlConnection
        'Dim connectionString As String = ""
        'Dim cmd As SqlCommand

        'connectionString = "Data Source=DEV\SQLEXPRESS;Initial Catalog=myDatabase;Trusted_Connection=True;"
        'con = New SqlConnection(connectionString)

        'cmd = New SqlCommand("INSERT INTO blobs VALUES(@filename,@filecontents)", con)
        'cmd.Parameters.Add("@filename", SqlDbType.VarChar).Value = uploadFile
        'cmd.Parameters.Add("@filecontents", SqlDbType.VarBinary).Value = fileContents
        'con.Open()
        'cmd.ExecuteNonQuery()
        'con.Close()


        ' Or write it to the filesystem:
        Dim writeStream As FileStream = New FileStream("C:\DownloadedFiles\" & uploadFile, FileMode.Create)

        'BLL.WriteLog("7")
        Dim bw As New BinaryWriter(writeStream)
        bw.Write(fileContents)
        bw.Close()

        'BLL.WriteLog("8")

        ' it all worked ok so send back SUCCESS is true!
        Return "{""success"":true}"
        Exit Function

upload_error:
        Return "{""error"":""An Error Occured""}"
    End Function

End Class
于 2018-05-26T08:24:50.987 回答