ajax发送FormData c#WebMethod

时间:2016-11-16 21:04:47

标签: c# jquery ajax file webmethod

我有一个带有文件输入和一个按钮的表单,当我按下按钮时,文件应该转到服务器端。

当我向服务器发送文件时,ajax响应成功,永远不会停止在我使用的c#webmethod断点中。我做错了什么?

表格:(Default.aspx)

<form id="form1" runat="server" enctype="multipart/form-data">
    <div align="center" class="divBody">
        <div id="controlHost">
            <div id="outerPanel">
                <table width="100%" cellpadding="2" cellspacing="5">
                    <tr align="left">
                        <td colspan="2">
                            <span class="message">Seleccione el archivo que desea subir</span>
                        </td>
                    </tr>
                    <tr align="left">
                        <td valign="top">
                            <input type="file" id="FileInput" multiple="false" class="fileInput" />
                        </td>
                        <td align="right">
                            <input type="button" id="btnUpload" name="btnUpload" value="Upload" onclick="sendFile();" class="button" />
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</form>

脚本:(Default.aspx)

function sendFile() {
    var data = new FormData();
    var file = $("#FileInput")[0].files[0];
    data.append("name", file.name);
    data.append("size", file.size);
    data.append("type", file.type);
    data.append("file", file);

    $.ajax({
            type: "POST",
            async: true,
            url: "Default.aspx/UploadBlock",
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            success: function (result) {
                alert("Success: " + result);
            },
            error: function (xhr, status) {
                alert("An error occurred: " + status);
            }
        });
};

WebMethod:(Default.aspx.cs)

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Respuesta UploadBlock()
{
  Respuesta res = new Respuesta { Success = true, Message = "OK" }; //Break point here
  return res;
}

感谢。

1 个答案:

答案 0 :(得分:0)

万一有人像我一样遇到这个问题...

WebMethods希望使用application / json的内容类型-https://stackoverflow.com/a/25531233/2913189

如果将content-type设置为false,则ajax调用将不会触发您的web方法,它将转到page_load。似乎还有其他方法可以通过对文件进行字符串化来完成文件上传,但是我无法获得有效的解决方案,因此我只创建了一个HttpHandler(.ashx)文件,进行了编译,并在web.config中添加了引用。

使用处理程序,可以在ajax调用中将content-type设置为“ false”,而不会出现任何问题。我以FormData形式发送了该信息,使用context.Request.Files和context.Request

可以轻松地在处理程序中使用它。

ajax调用的片段:

var fileControl = $("#file")[0].files[0];
var formData = new FormData();
formData.append("employeeId", employeeId);
formData.append("userfile", fileControl);
formData.append("filetype", uploadTypeSelect.val());

$.ajax({
                        type: "POST",
                        contentType: false,
                        url: "/Handlers/MyUploadHandler.ashx",
                        processData: false,
                        data: formData,
                        success: function (msg) {
                            //do something
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            //do something
                        }
                    });

处理程序的片段

public override async Task ProcessRequestAsync(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var uploadedFile = context.Request.Files[0]; //only uploading one file
            var fileName = uploadedFile.FileName;
            var fileExtension = uploadedFile.ContentType;
            var folder = "MyOneDriveFolder";

            //this is an method written elsewhere to upload a file to OneDrive
            var uploaded = await OneDriveUpload.UploadDocument(filename,uploadedFile.InputStream, folderName, 0);

            context.Response.Write("Whatever you like");
        }