Javascript 使用 JQuery 和 ASP.NET 通用处理程序上传文件 - 有可能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4972607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:01:56  来源:igfitidea点击:

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

javascriptjqueryasp.netjquery-pluginsfile-upload

提问by bleepzter

I am trying to solve a small issue. I have built an entire web ASP.NET application using mostly client side (JQuery/JavaScript) code. I use generic handlers to do some lazy loading of data, as well as for auto-completes and the likes.

我正在尝试解决一个小问题。我主要使用客户端 (JQuery/JavaScript) 代码构建了一个完整的 Web ASP.NET 应用程序。我使用通用处理程序来做一些数据的延迟加载,以及自动完成等。

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. I researched a whole ot of plugins but they all rely on having a php backend.

我想知道是否有办法完全从 JQuery/JavaScript 上传文件。我研究了一大堆插件,但它们都依赖于有一个 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.Paramscollection 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. Therefore I would be sending a string to my server with the filename, not an array of bytes.

然而,问题是我不知道这将如何工作,因为 FileUpload html 控件仅将文件名存储在其值中。因此,我将使用文件名将字符串发送到我的服务器,而不是字节数组。

Any thoughts on this would be greatly appreciated!

对此的任何想法将不胜感激!

回答by Zitun

I'm using the uploadify plugin (http://www.uploadify.com/) - as Jeremy said, it's not in javascript - It's not possible. It's in flash. It's very easy to install.

我正在使用 uploadify 插件 (http://www.uploadify.com/) - 正如 Jeremy 所说,它不在 javascript 中 - 这是不可能的。它在闪光。安装非常容易。

$('#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 找到的最好的解决方案

回答by Jeremy B.

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. Javascript cannot upload a file to a server, it can only decorate the built in html functionality. With that said I can only assume you are attempting to mimic ajax like uploading functionality. If that is so there is a way to upload files using an iframe which will look like you are using ajax.

当您将文件上传到服务器时,可以归结为三个选项。您可以使用原生 html 文件上传功能、Flash 或 Java。Javascript 不能将文件上传到服务器,它只能装饰内置的 html 功能。话虽如此,我只能假设您正在尝试模仿 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. You can hook up your jquery to process the response the iframe returns and handle user information.

此表单使用 iframe 发布文件,这将导致主页永远不会刷新。您可以连接您的 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.

如果这不是您正在寻找的等式的一部分,请随时发表评论并澄清您要完成的任务。

回答by Luke Bennett

If you can dictate which browsers your app is accessed through (e.g. it's an internal business app), it's worth checking out the new File APIwhich is part of the "HTML5" stack of technologies that are beginning to show up in the latest browsers. This gives you direct access to files via clientside Javascript without the need to post the file to the server first.

如果您可以指定通过哪些浏览器访问您的应用程序(例如,它是一个内部业务应用程序),那么值得查看新的File API,它是“HTML5”技术堆栈的一部分,这些技术开始出现在最新的浏览器中。这使您可以通过客户端 Javascript 直接访问文件,而无需先将文件发布到服务器。

If your app is public-facing then you can still use the File API, but you will need to check for supportfor it in your code and apply some kind of fallback mechanism (such as Uploadify) for those with older browsers.

如果您的应用面向公众,那么您仍然可以使用 File API,但您需要在代码中检查对它的支持,并为那些使用较旧浏览器的应用应用某种回退机制(例如Uploadify)。

You can read more about the File API hereand hereamongst other places.

您可以在此处此处以及其他地方阅读有关 File API 的更多信息。

回答by Chris B. Behrens

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. Several popular uploaders use this method...my favorite is Uploadify. Take a look at that, and see if that doesn't suit your needs.

因此,您无法使用本机输入 type=file 或使用预先存在的桌面字节,例如 Flash。几个流行的上传者使用这种方法......我最喜欢的是Uploadify。看一看,看看它是否不适合您的需求。

HTH.

哈。

回答by Syed Bashar

I have implemented an ASP.NET Handler for uploading file using Valums ajax Upload control. You can check solution here. You can also upload large file. This handler supports IE, FF and Chrome browser. You can also drag drop multiple files from FF and Chrome (HTML 5)

我已经实现了一个 ASP.NET 处理程序,用于使用 Valums ajax 上传控件上传文件。您可以在此处查看解决方案。您也可以上传大文件。此处理程序支持 IE、FF 和 Chrome 浏览器。您还可以从 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-valuems.html

回答by Vando

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