简体   繁体   English

使用JQuery和ASP.NET Generic Handler上传文件 - 是否可能?

[英]File upload with JQuery and ASP.NET Generic Handler - Is it possible?

I am trying to solve a small issue. 我正在努力解决一个小问题。 I have built an entire web ASP.NET application using mostly client side (JQuery/JavaScript) code. 我使用大多数客户端(JQuery / JavaScript)代码构建了一个完整的Web ASP.NET应用程序。 I use generic handlers to do some lazy loading of data, as well as for auto-completes and the likes. 我使用通用处理程序来做一些延迟加载的数据,以及自动完成等。

One of the requirements is that one page needs to be able to upload a file, as well as display meta information about the uploadead files. 其中一个要求是一个页面需要能够上传文件,以及显示有关uploadead文件的元信息。

I as wondering if there is a way to upload a file entirely out of JQuery/JavaScript. 我想知道是否有办法完全从JQuery / JavaScript上传文件。 I researched a whole ot of plugins but they all rely on having a php backend. 我研究了很多插件,但它们都依赖于php后端。

My thought was to create a post: 我的想法是创建一个帖子:

$(function(){
    $('#submit').live('click', function(event){

        $.post('/SomeOtherHandler.ashx',  //can be '/someotherpage.aspx'
        { 
            filename: $('#fileUpload').val(), 
            timestamp: (new Date()).toString() 
        }, function(data){
             //do something if the post is successful.
        });

    });
});

Would that work? 那会有用吗? I know that if you include the json object { filename: value, timestamp: value } it will show up in the HttpContext.Request.Params collection where I can read it without problems. 我知道,如果你包含json对象{ filename: value, timestamp: value } ,它将显示在HttpContext.Request.Params集合中,我可以毫无问题地阅读它。

The problem is however that I don't know how this will work since the FileUpload html control only stores the file name in its value. 但问题是我不知道这是如何工作的,因为FileUpload html控件只将文件名存储在其值中。 Therefore I would be sending a string to my server with the filename, not an array of bytes. 因此,我将使用文件名向我的服务器发送一个字符串,而不是字节数组。

Any thoughts on this would be greatly appreciated! 对此有任何想法将不胜感激!

I'm using the uploadify plugin (http://www.uploadify.com/) - as Jeremy said, it's not in javascript - It's not possible. 我正在使用uploadify插件(http://www.uploadify.com/) - 正如Jeremy所说,它不是在javascript中 - 这是不可能的。 It's in flash. 它在闪光灯中。 It's very easy to install. 这很容易安装。

$('#file_upload').uploadify({
   'uploader'  : '/uploadify/uploadify.swf',
   'script'    : '/uploadify/uploadify.ashx',
   'cancelImg' : '/uploadify/cancel.png',
   'folder'    : '/uploads',
   'auto'      : true,      
   'fileExt': '*.xls;*.xlsx;*.csv',
   'buttonText': 'Select your file',
   'onError'     : function (event,ID,fileObj,errorObj) {

  alert(errorObj.type + ' Error: ' + errorObj.info);

},
'onComplete'  : function(event, ID, fileObj, response, data) 
                {
                    var obj = jQuery.parseJSON(response);
                    if (obj.error != "" & obj.errror != null)
                    {
                        lblTable.html("error : " + obj.error);
                    }
                    else


                    {
                        lblTable.html(obj.table);
                       lblEditData.show();
                       lblTable.hide();
                    }

                }
 });

And on the uploadify.ashx : 在uploadify.ashx上:

public class uploadify : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        System.Web.HttpPostedFile file = context.Request.Files["Filedata"];

        //Check extension
        string extension = "";
        try
        {
            extension = file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
            if (extension != "xls" & extension != "xlsx" & extension != "csv") throw new Exception("Error of the extension");
        }
        catch
        {
            context.Response.Write("{\"error\",\"Error with the extension of the file\"");
        }


        string linkFile = System.Web.HttpContext.Current.Server.MapPath("~") + "uploads" + "\\" + DateTime.Now.ToString("yyMMddHHmm") + APIReportPro.DocumentPDF.RandomString(4) + "." + extension;

        file.SaveAs(linkFile);


  ...etc...

This is the nicest solution I found for asp.net 这是我为asp.net找到的最好的解决方案

You have what boils down to three options when you are uploading files to a server. 将文件上载到服务器时,您可以归结为三个选项。 You can use native html file-upload features, Flash or Java. 您可以使用本机html文件上传功能,Flash或Java。 Javascript cannot upload a file to a server, it can only decorate the built in html functionality. Javascript无法将文件上传到服务器,它只能装饰内置的html功能。 With that said I can only assume you are attempting to mimic ajax like uploading functionality. 有了这个说我只能假设你试图像上传功能一样模仿ajax。 If that is so there is a way to upload files using an iframe which will look like you are using ajax. 如果是这样,有一种方法可以使用iframe上传文件,看起来你正在使用ajax。

You will be creating a form 您将创建一个表单

<form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.aspx">
    <input name="file" id="file" size="27" type="file" /><br />
    <input type="submit" name="action" value="Upload" /><br />
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>

This form uses the iframe to post the file, which will cause the main page to never refresh. 此表单使用iframe发布文件,这将导致主页永远不会刷新。 You can hook up your jquery to process the response the iframe returns and handle user information. 您可以连接jquery来处理iframe返回的响应并处理用户信息。

If this is not the part of the equation you were looking for please feel free to comment and clarify what it is you are looking to accomplish. 如果这不是你想要的等式的一部分,请随意评论并澄清你想要完成的是什么。

If you can dictate which browsers your app is accessed through (eg it's an internal business app), it's worth checking out the new File API which is part of the "HTML5" stack of technologies that are beginning to show up in the latest browsers. 如果您可以指定您的应用程序通过哪些浏览器访问(例如,它是一个内部业务应用程序),那么值得查看新的File API ,它是“HTML5”技术堆栈的一部分,这些技术开始出现在最新的浏览器中。 This gives you direct access to files via clientside Javascript without the need to post the file to the server first. 这使您可以通过客户端Javascript直接访问文件,而无需先将文件发布到服务器。

If your app is public-facing then you can still use the File API, but you will need to check for support for it in your code and apply some kind of fallback mechanism (such as Uploadify ) for those with older browsers. 如果您的应用程序是面向公众的,那么您仍然可以使用文件API,但是您需要在代码中检查是否支持它,并为那些使用旧浏览器的人应用某种回退机制(例如Uploadify )。

You can read more about the File API here and here amongst other places. 您可以在此处以及此处以及其他位置阅读有关File API的更多信息。

I'm pretty sure it's not possible; 我很确定这是不可能的; if it is then it's a big security hole - Javascript should not be able to get bytes from the user's hard drive. 如果它是一个很大的安全漏洞 - Javascript不应该从用户的硬盘驱动器中获取字节。

So you're stuck using the native input type=file or using pre-existing desktop bytes, like Flash. 因此,您使用本机输入类型=文件或使用预先存在的桌面字节(如Flash)。 Several popular uploaders use this method...my favorite is Uploadify . 几个流行的上传者使用这种方法...我最喜欢的是Uploadify Take a look at that, and see if that doesn't suit your needs. 看一下,看看是否符合您的需求。

HTH. HTH。

I have implemented an ASP.NET Handler for uploading file using Valums ajax Upload control. 我已经使用Valums ajax上传控件实现了一个ASP.NET Handler来上传文件。 You can check solution here. 您可以在此查看解决方案。 You can also upload large file. 您也可以上传大文件。 This handler supports IE, FF and Chrome browser. 此处理程序支持IE,FF和Chrome浏览器。 You can also drag drop multiple files from FF and Chrome (HTML 5) 您还可以从FF和Chrome中拖放多个文件(HTML 5)

http://ciintelligence.blogspot.com/2011/05/aspnet-server-side-handler-for-valums.html http://ciintelligence.blogspot.com/2011/05/aspnet-server-side-handler-for-valums.html

Using jquery you can do something like: 使用jquery你可以做类似的事情:

<input type="file" name="file" id="file1" runat="server" />

$("#<%=file1.ClientID%>").change(function () {
  //Do stuff
   $(this).upload('youHandler.ashx', function (res) {
     //do stuff on success
   }
}

Now on yourHandler.ashx you can do something like that: 现在在yourHandler.ashx上你可以做类似的事情:

public void ProcessRequest(HttpContext context)
{
   if (context.Request.Files.Count > 0)
   {
      var fileCount = context.Request.Files.Count;
      var fileStram = var file = context.Request.Files[0].InputStream;

      //Do whatever you want
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM