1

i use Filesaver.js to try to download files from my backend, which is on Express (nodejs).

Here is my backend code to download files. It uses a middleware to check the auth info.

res.download(url, function (err) {
   if (err) {
      console.log("Error: " + err);
      res.status.send({
         message: "Can not download file"
      });
   }
});

And here is the code of my service:

downloadEventAttachment(attachmentUrl){

    let endPointUrl = this.auth.getServerHost();

    this.authHttp.get(endPointUrl + attachmentUrl)
        .subscribe(res => {
            var blob = new Blob([res], { type: res.headers.get('Content-Type') });
            saveAs(blob);
        }) 
}

The problem is that generates a download file but with errors. If i download a image it says that the image is not valid.

enter image description here

If i try to download a txt file its have this content:

Response with status: 200 OK for URL: http://192.168.1.78:8081/calendar/download_eventattachment/728/file-1496421767591.txt

If i use this request from postman, then the image is well displayed.

enter image description here

I'm doing something wrong?

Thanks a lot

[UPDATE 1]

I add the responseType and still not working:

downloadEventAttachment(attachmentUrl){
        let endPointUrl = this.auth.getServerHost();

        let options = new RequestOptions({ responseType: ResponseContentType.Blob });

        this.authHttp.get(endPointUrl + attachmentUrl, options)
            .subscribe(res => {

                var blob = new Blob([res], { type: res.headers.get('Content-Type') });
                saveAs(blob);
            },
            error => {
                console.log(error);
            })
    }
4

1 Answer 1

1

Finally works on this way:

downloadEventAttachment(attachmentUrl){
    let endPointUrl = this.auth.getServerHost();
    let options = new RequestOptions({ responseType: ResponseContentType.Blob });
    this.authHttp.get(endPointUrl + attachmentUrl, options)
        .subscribe(res => {
                var file = res.blob();
            });
            saveAs(file);
        },
        error => {
            console.log(error);
        })
}

I think that the older line: var blob = new Blob([res], { type: res.headers.get('Content-Type') });

Was overlapping the content of the response.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.