下载带有角度2的文件

时间:2017-02-27 06:56:19

标签: angular asp.net-web-api

我正在尝试从服务器下载文件。它可能是.pdf, .xslx, .docx等我有这个代码:

    [HttpGet]
    public HttpResponseMessage DownloadFile(int Id)
    {
        var file = Uow.Files.GetSingleById(Id);

        if (file == null)
        {
            throw new ArgumentException("File not found");
        }

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

        var stream = new FileStream(String.Concat(RepositoryPath.Root, file.PhysicalPath), FileMode.Open);
        result.Content = new StreamContent(stream);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        return result;
    }

如果我点击下载响应是这样的: enter image description here

并在angular2:

downloadFile(id: number) {
        this.httpCall.get('/pub/page/DownloadFile/' + id).subscribe();
}

在httpcall服务中:

private headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Language': this.ls.actLan });

get(url: string): Observable<any> {
    return this.http.get(this.baseUrl + url, { headers: this.headers })
        .map(this.extractData)
        .catch(this.handleError);
}
private extractData(res: Response) {
    let body = res.json();
    return body.data || {};
}
private handleError(error: Response | any) {
    console.log('error');
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
}

在web.config中我启用了cors

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, HEAD" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
</httpProtocol>

当我点击下载按钮时,它说:

  

位置0的JSON中出现意外的标记%

怎么了?

0 个答案:

没有答案
相关问题