I'm trying to download file from server. it may be .pdf, .xslx, .docx
etc. I have this code:
[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;
}
and if I click to download response is this:
and in angular2:
downloadFile(id: number) {
this.httpCall.get('/pub/page/DownloadFile/' + id).subscribe();
}
in httpcall service:
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);
}
and in web.config I have cors enabled
<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>
When I click to download button it says:
Unexpected token % in JSON at position 0
What's wrong?