上传文件后,我试图返回 JSON 结构。该文件很好地保存在网络服务器中。问题是当我尝试使用结构“UploadJobStatus”返回数据时,IE 会提示我保存文件:“你想从 localhost 打开还是保存 UploadFile554b0687?” 该文件首先保存在 Web 服务器中,然后我收到带有奇怪文件名的提示问题。如果我保存文件,我会看到内容是返回的 JSON 数据:
[{"Error":"上传文件成功。","Successful":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!");
}
}
)
}
}
有任何想法吗?谢谢