gpt4 book ai didi

javascript - 如何使用 window.open() 下载文件

转载 作者:行者123 更新时间:2023-12-03 02:23:12 26 4
gpt4 key购买 nike

我正在尝试使用 window.open(path,'_blank','download') 从服务器下载文件,但它只是在新选项卡中打开它。我如何下载该文件?是的,我确实检查了其他类似的问题,但没有一个有效。我也尝试过 this但没有成功。

$scope.docView = function () {     
Method.getbyId("api call",docId).then(function(response) {
}).catch(function (data) {
console.log("Unknown Error");
});
}
}

/*this.getbyId = function (path, id) {
return $http.get(appSetting.apiBaseUrl + path + "/" + id);
};
*/




[Route("api call")]
[HttpGet]
public IHttpActionResult ViewDocument (Guid? docId)
{
/*background work*/

response.Message = filePath;
var bytes=System.IO.File.ReadAllBytes(prevPath);
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = value.Format;
string Name = value.DocumentName;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + Name);
HttpContext.Current.Response.BinaryWrite(bytes);
}
}
catch (Exception ex)
{
Utils.Write(ex);
}

return Ok(response);
}

最佳答案

要强制浏览器下载文件(而不是在另一个选项卡或当前选项卡中显示它),需要随文件正文一起发送特殊 header 。

只有当您可以在服务器端修改某些内容时,这才有可能。

您应该发送以下 header :

  • Content-Disposition: attachment; filename"myfile.txt"
  • Content-Type: application/octet-stream; name="myfile.txt"
  • Content-Transfer-Encoding: binary

当然,替换application/octet-stream根据文件的内容类型(如果已知)( application/pdfimage/jpeg 等)

关于javascript - 如何使用 window.open() 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49065549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com