【问题标题】:Send File with extra parameters to WCF REST Service将带有额外参数的文件发送到 WCF REST 服务
【发布时间】:2016-08-24 17:09:36
【问题描述】:

我在这里遇到了一个小问题。

目前我正在使用通用处理程序将文件上传到服务器,但我遇到的一个问题是,如果我有额外的数据,例如用户名和姓氏,我必须单独执行(保存)。

这是一个问题,因为如果我保存姓名和姓氏,并且文件上传失败,我的数据库中有一条记录没有与之关联的文件。

所以,现在我正在考虑实现一个新的 Web 方法,它将承担所有这些,如果该方法失败,它只会回滚 SQL 事务。

我要做的是调用一个web方法,并传递带有用户名和姓氏和照片的文件,然后在那里执行保存到数据库中。

这是我尝试过的:

jQuery:

$("#btnCreateRequest").click(function () {
    var data = new FormData();
    var photo = $("#fuPhoto")[0].files[0];

    data.append("name", 'Fred');
    data.append("surname", 'Moller');
    data.append("photo", photo);

    $.ajax({
        type: "POST",
        url: "Service.svc/CreateRequest",
        dataType: "json",
        //cache: false,
        contentType: false,
        processData: false,
        data: data,
        success: function (response2) {
            //$("#PageArea").html(response2);
            Popup(true, "success", "success", true);
        },
        error: function (response) {
            Popup(true, "Error", JSON.stringify(response), true);
        }
    });
});

IService.cs

[OperationContract]
[WebInvoke(Method = "POST",
    UriTemplate = "CreateRequest",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string CreateRequest();

服务.svc

public string CreateRequest()
{
    var request = System.Web.HttpContext.Current.Request;

    string name = request["name"];
    string surname = request["surname"];
    HttpPostedFile photo = request["photo"];

    //Saving in database happens here, using above variables...

    return "whatever";
}

但是,我失败得很惨。

Web 服务被调用,但所有变量均为 NULL。

如果我以错误的方式解决此问题,请指出正确的方向 - 任何帮助将不胜感激!

(如果有不清楚的地方,请询问,我会尽力解释更多)

【问题讨论】:

  • 尝试将BodyStyle 设置为Bare
  • 刚刚试过 - 它仍然没有得到变量值:(

标签: c# jquery web-services wcf-rest


【解决方案1】:

啊,没关系,我改变了我的方法。我现在没有尝试使用 Web 服务,而是为此使用通用处理程序。

有时,最好换个角度看。 这是我如何让它为我工作的方法。

在我的 jQuery 中,我会有这样的东西:

$("#btnCreateRequest").click(function () {
        var data = new FormData();
        var photo = $("#fuPhoto")[0].files[0];

        data.append("callingFromPage", "help");
        data.append("requestType", $('#dropBugType').val());
        data.append("description", $('#taDescription').val());
        data.append("photo", photo);
        data.append("userGUID", _cookieObject.UserObject.GlobalUniqueID);

        $.ajax({
            xhr: function () {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        percentComplete = parseInt(percentComplete * 100);
                        //Indicate progress.
                        $('.uplPhotoProgress').css('width', percentComplete + '%');
                        $('.uplPhotoProgress').html('Uploading: ' + percentComplete + '%');
                        //Hide progress bar.
                        if (percentComplete === 100) {
                            $//('.uplProgressAttachments').css('display', percentComplete + 'none');
                        }

                    }
                }, false);
                return xhr;
            },
            url: "UploadHandler.ashx/",
            data: data,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (response) {
                if (response === 'success') {
                    console.log('success');
                } else {
                    console.log('problem...');
                }
            },
            error: function (response) {

            }
        });
    });

然后,在我的 UploadHandler.ashx(通用处理程序)中:

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "multipart/form-data";
        context.Response.Expires = -1;
        try
        {
            string callingFromPage = context.Request["callingFromPage"];
            if (!string.IsNullOrWhiteSpace(callingFromPage))
            {
                switch (callingFromPage)
                {
                    case "help":
                        {
                            string requestType = context.Request["requestType"];
                            string description = context.Request["description"];
                            HttpPostedFile photo = context.Request.Files[0];
                            string guid = context.Request["userGUID"];
                            //DO YOUR STUFF >>>
                            context.Response.Write("success");
                            break;
                        }
            }
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }

当然,这是我所做的一个简单示例……但我很高兴这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多