如何使用SVC处理ajax上传文件?

时间:2013-08-01 21:13:36

标签: c# jquery rest file-upload svc

我正在尝试使用jQuery Ajax将单个文件(而不是图像)上传到WCF Web服务(svc)。我终于把web.config用于传输,我的SVC正在收到一些东西,但我不知道如何获取和处理传入的表单内容......

<input id="ipt_file" type="file" />
<a href='#' onclick="UploadFile();" data-role='button'>Upload</a>

var UploadFile = function () {
    var file_object = $('#ipt_file')[0].files[0];
    var form_data = new FormData();
    form_data.append('file', file_object);

    var xhr_upload = $.ajax({
        type: "POST",
        headers: { "Cache-Control":"no-cache", "X-Session":"12345678" },
        url: "../Upload.svc/UploadJobFile",
        data: form_data,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (msg) {
            if (typeof (msg) === "object") {
                var _upload = $.parseJSON(msg.d);
                alert(_upload.status + ': ' + _upload.msg);
            };
        }
    });
};

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Upload
{
    [OperationContract(Name="UploadJobFile")]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedResponse, ResponseFormat = WebMessageFormat.Json)]
    [return: MessageParameter(Name = "d")]
    public string UploadJobFile() 
    {
        string response = string.Empty;
        HttpRequest request = HttpContext.Current.Request;
        string session_id = request.Headers["X-Session"];
        //
        // ??? need the request file or body
        //
        if (request.ContentLength > 0)
        {
            response = "OK, content length= " + request.ContentLength.ToString(); // works, returns ~ file size
        }
        else
        {
            response = "fail";
        }
        return response;
    }
}

不幸的是,request.Form [“file”],request.Form [0]和request.Params似乎不起作用,尽管有很多帖子我已经阅读过其他声明。如果我无法访问请求体,我无法创建一个字节数组,流,或声明它是一个HttpPostedFile ...(实际上我将要做的是设置一个新的请求传递它和一些额外的参数数据服务)。

我错过了什么?

0 个答案:

没有答案