简体   繁体   English

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

[英]How to download a file using window.open()

I am trying to download a file from server using window.open(path,'_blank','download') but it just opens it in a new tab. 我正在尝试使用window.open(path,'_ blank','download')从服务器下载文件,但它只是在新选项卡中将其打开。 How do I download the file? 如何下载文件? Yes I did check for other similar question but none of them work. 是的,我确实检查过其他类似的问题,但它们均无作用。 Also I've tried this but it didn't work. 我也试过了,但是没有用。

$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);
    }

To force the browser to download the file (instead of displaying it, in another tab or the current one) requires a special header to be sent along with the file body. 要强制浏览器下载文件(而不是在另一个选项卡或当前选项卡中显示文件),需要将特殊的标头与文件正文一起发送。

That's only possible if you can modify some things server-side. 仅当您可以在服务器端修改某些内容时,才有可能。

You should send following headers : 您应该发送以下标头:

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

Of course, replace application/octet-stream by the content-type of your file, if known ( application/pdf , image/jpeg , etc.) 当然,如果您知道文件的内容类型( application/pdfimage/jpeg等),请用文件的内容类型替换application/octet-stream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM