How to use Fine Uploader server-side in a non-MVC ASP.NET application

我只是一个虾纸丫 提交于 2020-01-01 06:24:08

问题


I have the following Fine Uploader code in markup in an aspx page in ASP.NET (not MVC) project:

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

For the client side piece, this works fine. I've modified the fineuploader.css to get the exact look I want (mostly). With the client side piece being done I just need to handle this in my code-behind by handling the request endpoint piece.

I've viewed several examples on the github page, but for ASP there are no non-MVC examples. Even the simplest of these examples involve creating a new class and inheriting from the Controller class. Since I'm not doing this site with MVC, how can I handle the server side aspect of this?

My client side piece is pretty much complete, and I can supply more info on my server side code and organization if necessary.


回答1:


Handling the requests sent by Fine Uploader is fairly trivial. All upload requests, by default, are multipart encoded POST requests. By default, all parameters are also present in the request payload as form fields.

I am not an ASP.NET developer, but it shouldn't be too difficult to handle MPE requests in ASP.NET. In fact, this is fairly trivial in most server-side languages. Here's an example of some code that should handle such a request:

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

}

Note that your server-side code must also return a valid JSON response. This is described more in Fine Uploader's server-side readme. There is an article on MSDN that describes dealing with JSON in .NET apps. Perhaps the JsonConvert class is required here.

You can read more about handling these requests at http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2.




回答2:


Kmarks2, it might be too late for you but this could help others.

To handle it server side in ASP.NET (not MVC) a WebHandler can be created. It is the Generic handler item with .ashx extension (e.g. FileUpload.ashx ).

The handler looks like this:

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

The endpoint should look like: 'http:// your server name/xxx/FileUpload.ashx' ( e.g.'http://localhost:3293/xxx/FileUpload.ashx')




回答3:


Working with ASP.NET which is not an MVC project a WebHandler is needed for handling request seamlessly. For examples and usage of WebHandler see here.

With reference to SanthoshM's answer and inline with the combination of Fine Uploader MVC VB.net Server-Side sample, this is what i came up with. I hope this may be helpful to someone.

Client 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>

Server Side

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


来源:https://stackoverflow.com/questions/16717201/how-to-use-fine-uploader-server-side-in-a-non-mvc-asp-net-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!