WCF / jQuery / HttpContext - 为什么我被提示保存文件?

时间:2013-05-22 16:29:00

标签: jquery wcf

我试图在上传文件后返回JSON结构。该文件保存在Web服务器中就好了。问题是当我尝试使用结构“UploadJobStatus”返回数据时,IE会提示我保存文件:“你想从localhost打开或保存UploadFile554b0687吗?” 该文件首先保存在Web服务器中,然后我收到带有奇怪文件名的提示问题。 如果我保存文件,我看到内容是返回的JSON数据:

[{“错误”:“成功上传文件。”,“成功”:true}]

但是,如果我更改我的界面只返回VOID,我不会得到提示。我需要返回该结构,以便我可以在jQuery代码中循环返回数据。

接口:

[System.Web.Services.WebMethod(EnableSession = true)]
[OperationContract(Name = "RunJob_UploadFile")]
[WebInvoke(UriTemplate = "/RunJob/UploadFile", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, Method = "POST")]
List<RunJob.UploadJobStatus> UploadFile();

代码:

      public List<UploadFileStatus> UploadFile()
      {
        List<UploadFileStatus> temp = new List<UploadFileStatus>();

        var files = System.Web.HttpContext.Current.Request.Files;
        if ((files.Count > 0) && (!String.IsNullOrEmpty(files[0].FileName)))
        {
            try
            {
                HttpContext.Current.Request.Files[0].SaveAs(@"C:\TEST\TEST.ZIP");
                temp.Add(new UploadFileStatus(true, "Uploaded file successfully."));
                return temp;
                //return;
            }
        catch (Exception e)
        {
            temp.Add(new UploadFileStatus(false, "Not able to upload the file!"));
            return temp;
        }
...

列表结构:

public struct UploadFileStatus
{
  public bool Successful;
  public string Error;

  public UploadFileStatus(bool successful, string error)
  {
      this.Successful = successful;
      this.Error = error;
  }
}

jQuery的:

function UploadFile() {
    if ($("#FileToUpload").val() != "") {
        $.ajaxFileUpload
            (
                {
                    url: "svc/RunJob.svc/RunJob/UploadFile",
                    secureuri: false,
                    fileElementId: "FileToUpload",
                    data:
                    {

                    },
                    success: function (jqXHR, textStatus) {
                        if (textStatus == "success") {
                            alert("File was uploaded.");
                        }
                        else {
                            alert("Upload file failed!");
                        }
                    },
                    error: function () {
                        alert("Error!");
                    }
                }
            )
    }
}

有什么想法吗? 谢谢

1 个答案:

答案 0 :(得分:0)

浏览器不了解返回的数据,因此提示您保存它,因为它不知道还有什么用它。

此问题中的信息应该有所帮助。 IE9 prompts user on submission of hidden iFrame