我正在尝试使用 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 等)


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!