Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在非MVC ASP.NET应用程序中使用Fine Uploader服务器端_Asp.net_Fine Uploader - Fatal编程技术网

如何在非MVC ASP.NET应用程序中使用Fine Uploader服务器端

如何在非MVC ASP.NET应用程序中使用Fine Uploader服务器端,asp.net,fine-uploader,Asp.net,Fine Uploader,我在ASP.NET(非MVC)项目的aspx页面中的标记中有以下优秀的上传程序代码: $(文档).ready(函数(){ var uploader=new qq.FineUploader({ 元素:$(“#精细上传程序”)[0], 请求:{/*处理Fine Uploader发送的请求相当简单。默认情况下,所有上载请求都是多部分编码的POST请求。默认情况下,所有参数也作为表单字段存在于请求负载中 我不是ASP.NET开发人员,但在ASP.NET中处理MPE请求应该不会太困难。事实上,在大多数服

我在ASP.NET(非MVC)项目的aspx页面中的标记中有以下优秀的上传程序代码:


$(文档).ready(函数(){
var uploader=new qq.FineUploader({
元素:$(“#精细上传程序”)[0],

请求:{/*处理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);
        }
    }

}
使用系统诊断;
Net系统;
使用System.Net.Http;
使用System.Threading.Tasks;
使用System.Web;
使用System.Web.Http;
公共类上载控制器:ApiController
{
公共异步任务PostFormData()
{
//检查请求是否包含多部分/表单数据。
如果(!Request.Content.IsMimeMultipartContent())
{
抛出新的HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root=HttpContext.Current.Server.MapPath(“~/App_Data”);
var provider=新的MultipartFormDataStreamProvider(根);
尝试
{
//读取表单数据。
wait Request.Content.ReadAsMultipartAsync(提供程序);
//这说明了如何获取文件名。
foreach(provider.FileData中的MultipartFileData文件)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine(“服务器文件路径:“+file.LocalFileName”);
}
返回Request.CreateResponse(HttpStatusCode.OK);
}
捕获(System.e例外)
{
返回请求.CreateErrorResponse(HttpStatusCode.InternalServerError,e);
}
}
}
请注意,您的服务器端代码还必须返回有效的JSON响应。这在中有详细描述。有一个描述在.NET应用程序中处理JSON的类。这里可能需要
JsonConvert


您可以在.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;
    }
}
}

使用制度;
使用System.Web;
使用System.IO;
公共类文件上载:IHttpHandler{
公共void ProcessRequest(HttpContext上下文)
{
//处理从客户端发送的文件
}
公共布尔可重用{
得到{
返回false;
}
}
}
端点应类似于: 'http://your server name/xxx/FileUpload.ashx'
(例如“)

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

参考作者的答案,并结合优秀的上传器MVC VB.net服务器端示例,这就是我的想法。我希望这对其他人有所帮助

客户端

<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

var existingHandler1=window.onload;
window.document.body.onload=函数(){
var galleryUploader=新qq.FineUploader({
元素:document.getElementById(“精细上传程序库”),
模板:“qq模板库”,
请求:{
端点:“../App_扩展名/FileUpload.ashx”
},
是的,
缩略图:{
占位符:{
waitingPath:“../App_Images/waiting generic.png”,
notAvailablePath:“../App_Images/not_available-generic.png”
}
},
验证:{
允许的扩展:['jpeg','jpg','gif','png'],
sizeLimit:3145728//3MB=3*1024*1024字节
},
重试:{
真的吗
},
});
如果(existingHandler1){existingHandler1()}
}
服务器端

<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

导入系统
导入系统.Web
导入System.IO
导入系统
导入系统。绘图
公共类文件上载:实现IHttpHandler
Public Sub-ProcessRequest(ByVal上下文作为HttpContext)实现IHttpHandler.ProcessRequest
context.Response.ContentType=“text/plain”
'context.Response.Write(“Hello World”)
Dim reader As StreamReader=新StreamReader(context.Request.InputStream)
尝试
将值设置为String=DateTime.Now.millis秒.ToString+Rnd(10000).ToString+.jpg“'reader.ReadToEnd()
“”BLL.WriteLog(值)
'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(值)
Dim responseText作为字符串=上载(值、上下文)
'BLL.WriteLog(responseText)
context.Response.Write(responseText)
'context.Response.Write(“{”“错误”“:”“发生错误”“}”)
特例
'BLL.WriteLog(例如Message+ex.StackTrace)
结束尝试
端接头
公共只读属性IsReusable()作为布尔值实现IHttpHandler.IsReusable
得到
返回错误
结束
端属性
函数上载(ByVal uploadFile作为字符串,ByVal上下文作为HttpContext)作为字符串
“所有书面记录(“1”)
错误时转到上载\u错误