【问题标题】:FileUpload using Jquery Ajax and Generic Handler使用 Jquery Ajax 和通用处理程序的文件上传
【发布时间】:2013-09-06 10:48:59
【问题描述】:

大家好,我是 asp.net fileUploader 的初学者,我正在使用打击代码上传:

HTML:

<asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" />
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload Selected File(s)" />

JavaScript 代码:

$("#Button1").click(function (evt) {
    var fileUpload = $("#FileUpload1").get(0);
    var files = fileUpload.files;
    var data = new FormData();

    for (var i = 0; i < files.length; i++) {
        data.append(files[i].name, files[i]);
    }

    var options = {};
    options.url = "FileUploadHandler.ashx";
    options.type = "POST";
    options.data = data;
    options.contentType = false;
    options.processData = false;
    options.success = function (result) { alert(result); };
    options.error = function (err) { alert(err.toString()); };

和处理程序代码:

if (context.Request.Files.Count > 0)
{
    HttpFileCollection files = context.Request.Files;
    for (int i = 0; i < files.Count; i++)
    {
        HttpPostedFile file = files[i];
        string fname = context.Server.MapPath("~/uploads/" + file.FileName);

        file.SaveAs(fname);
    }
}

context.Response.ContentType = "text/plain";
context.Response.Write("File(s) Uploaded Successfully!");

我有两个问题,第一个是在 web 应用程序的根目录中找不到上传文件,第二个是页面回发 有没有人帮助我解决我的问题谢谢!

【问题讨论】:

    标签: asp.net jquery upload


    【解决方案1】:

    我自己对 jQuery-File-Upload 有点困惑,但在查看插件文档后,我发现插件在 Windows 环境下工作需要什么。

    问题 1:文件保存 - 关于此问题,请确保您保存到一个有效且先前创建的目录,并且您对该目录具有 WRITE 权限。

    问题 2:上传回发 - 您必须设置上传脚本来写入上传的文件,并向插件返回有效的 JSON 响应,如插件文档中所定义:https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler

    if (context.Request.Files.Count > 0) {
        HttpFileCollection files = context.Request.Files;
        for (int i = 0; i < files.Count; i++) {
            HttpPostedFile file = files[i];
            string fname = context.Server.MapPath("~/uploads/" + file.FileName);
            file.SaveAs(fname);
        }
    }
    
    upload_response = '{"files":[{"name": ' + file.FileName + '","size":' file.FileSize + ',"url":"http:\/\/example.org\/files\/ + file.FileName + ",'
    upload_response =+ '"thumbnailUrl": "http:\/\/example.org\/files\/thumbnail\/ + file.FileName + ","deleteUrl": "http:\/\/example.org\/files\/ + file.FileName + ",'
    upload_response =+ '"deleteType": "DELETE"}]}"'
    
    context.Response.ContentType = "application/json";
    context.Response.Write( upload_response );
    

    请注意,我还将 ContentType 更改为“application/json”。这段代码的语法可能不完整,但最重要的是输出插件需要的这些JSON字段。

    【讨论】:

      猜你喜欢
      • 2013-06-11
      • 2013-06-02
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 2018-04-15
      • 2012-06-11
      • 2013-02-20
      相关资源
      最近更新 更多