【问题标题】:Upload a file by posting a file in jquery ajax to an asmx通过将 jquery ajax 中的文件发布到 asmx 来上传文件
【发布时间】:2015-08-22 19:16:45
【问题描述】:

我正在尝试通过网络服务 (ASMX) 上传文件

我写的web服务如下

[WebMethod]
public string UploadProducts(string Title, Stream documentStream)

我在客户端写了一个脚本如下

        var data = new FormData(),
        file = $("#fileUpload")[0].files[0]; // an input of type file
        if (file != null) {
            data.append("Title", "demotitle");
            data.append("documentStream", files[0]);
            $.ajax(
            {
                url: "FileManager.asmx/UploadFile",
                dataType: "json",
                type: "POST",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                success: function () {alert('done') },
                error: function () { alert('error'); }
            });

这似乎不起作用。如果有人能指导我哪里做错了,那就太好了。在此先感谢:)

【问题讨论】:

  • 请定义“不工作”。任何 javascript 错误?您是否在浏览器控制台中看到 POST 请求?您的网络方法中的断点是否命中?你收到 javascript alert() 了吗?
  • 感谢@Mr.White,看来由于网络方法需要一个 Stream 对象,当前发布文件的方式会导致 500 错误
  • 错误说明了什么?
  • 您要发送的文件类型是什么?根据我的经验,$.ajax( 不适用于图像/视频等二进制数据

标签: jquery ajax web-services asmx


【解决方案1】:

删除代码中的dataType:json

var data = new FormData(),
file = $("#fileUpload")[0].files[0]; // an input of type file
if (file != null) {
    data.append("Title", "demotitle");
    data.append("documentStream", files[0]);
}
$.ajax(
{
    url: "FileManager.asmx/UploadFile",
    type: "POST",
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    success: function () {alert('done') },
    error: function () { alert('error'); }
});

这应该可行。

【讨论】:

    猜你喜欢
    • 2010-12-13
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    相关资源
    最近更新 更多