ajax发送FormData c#WebMethod

Iva*_*ias 5 c# ajax jquery 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>
Run Code Online (Sandbox Code Playgroud)

脚本:(默认.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);
            }
        });
};
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢。

小智 3

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

WebMethods 需要 application/json 的内容类型 - /sf/answers/1787186341/

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

使用处理程序,您可以在 ajax 调用中将内容类型设置为“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
                        }
                    });
Run Code Online (Sandbox Code Playgroud)

处理程序的片段:

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");
        }
Run Code Online (Sandbox Code Playgroud)