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

时间:2018-03-02 08:46:31

标签: javascript angularjs asp.net-mvc

我正在尝试使用window.open(路径,' _blank',#39; 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);
    }

1 个答案:

答案 0 :(得分:1)

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

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

您应该发送以下标题:

  • ProductClass
  • saveProductMethod
  • employees = [ { "id":"101", "name": "abc", "mobile":"123" }, { "id": "102", "name": "xyz" }

当然,请将for employee in employees: print employee['mobile'] 替换为您文件的内容类型(如果已知(Content-Disposition: attachment; filename"myfile.txt"Content-Type: application/octet-stream; name="myfile.txt"等)。