使用JavaScript从POST on web API保存返回文件

使用JavaScript从POST on web API保存返回文件,javascript,.net,Javascript,.net,我正在尝试保存从.Net web api返回的文件。我可以使用get请求,只返回一个文件,但我想随文件返回一个对象,如果在创建文件时发生错误,该对象将包含错误信息。如果需要,我可以提供更多的代码 这很有效 [HttpGet] public async Task<HttpResponseMessage> GetFile(string reportAddress) { // Previous code left out .... objResponse.Con

我正在尝试保存从.Net web api返回的文件。我可以使用get请求,只返回一个文件,但我想随文件返回一个对象,如果在创建文件时发生错误,该对象将包含错误信息。如果需要,我可以提供更多的代码

这很有效

[HttpGet]
public async Task<HttpResponseMessage> GetFile(string reportAddress)
{

    // Previous code left out
    ....

    objResponse.Content = new StreamContent(new FileStream(mappedPath, FileMode.Open, FileAccess.Read));
    objResponse.Content.Headers.ContentDisposition = new 
    System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    objResponse.Content.Headers.ContentDisposition.FileName = filename;
    return objResponse;
}

   // click function ...
    .....
    var webApiAddress = currentUrl + "/api/Pdf/GetFile/" + reportAddress1 + "/";
    
    // this saves the file
    window.location = webApiAddress;

[HttpGet]
公共异步任务GetFile(字符串reportAddress)
{
//以前的代码遗漏了
....
objResponse.Content=newstreamcontent(newfilestream(mappedPath,FileMode.Open,FileAccess.Read));
objResponse.Content.Headers.ContentDisposition=new
System.Net.Http.Headers.ContentDispositionHeaderValue(“附件”);
objResponse.Content.Headers.ContentDisposition.FileName=文件名;
返回objResponse;
}
//单击函数。。。
.....
var webApiAddress=currentUrl+“/api/Pdf/GetFile/”+reportAddress1+“/”;
//这将保存文件
window.location=webApiAddress;
尝试了一个帖子,虽然不需要。但这并不奏效。但是文件会返回,并且可以在控制台中看到。显然,这里我没有返回JSON对象,只是返回一个文件,但即使如此,它也不会保存下载。如有任何帮助,我们将不胜感激

....
[HttpPost]
public async Task<HttpResponseMessage> GetFilep(PdfFileViewModel pdfFileViewModel)
{
    // Previous code left out
    ....
    objResponse.Content = new StreamContent(new FileStream(mappedPath, FileMode.Open, FileAccess.Read));
    objResponse.Content.Headers.ContentDisposition = new 
    System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    objResponse.Content.Headers.ContentDisposition.FileName = filename;
    return objResponse;

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: "../api/pdf/GetFilep",
    contentType: "application/json"
  }).done(function (res) {
   // this does not save the file           
      window.location = res;
   });
 }
。。。。
[HttpPost]
公共异步任务GetFilep(PdfFileViewModel PdfFileViewModel)
{
//以前的代码遗漏了
....
objResponse.Content=newstreamcontent(newfilestream(mappedPath,FileMode.Open,FileAccess.Read));
objResponse.Content.Headers.ContentDisposition=new
System.Net.Http.Headers.ContentDispositionHeaderValue(“附件”);
objResponse.Content.Headers.ContentDisposition.FileName=文件名;
返回objResponse;
$.ajax({
类型:“POST”,
数据:JSON.stringify(模型),
url:“../api/pdf/GetFilep”,
contentType:“应用程序/json”
}).完成(功能(res){
//这不会保存文件
window.location=res;
});
}