1

I am trying to figure out how i can transfer a file from my web api to my angular 5 front end and download it.

My Angular 5 front end is simple (i am using FileSaver package to help):

filedownload.component.html

<button (click)="downloadFile(document)">Download</button>

filedownload.component.ts

downloadFile(document) {
    this.http.get("http://localhost:8080/"+document.id+).subscribe(
     data => {
          const dataFile = data;
          saveAs(dataFile, document.filename);
     },
     err => { console.info(err); }
     );
}

On my web api i have no idea how to construct the response. So far i only have:

[HttpGet("{id}"]
public async Task<IActionResult> GetFile(Guid id) {
    var testFileInfo = _dbcontext.UploadedFile.GetById(id);
    var filePath = Path.Combine("C:\FileRepo", testFileInfo.Filename);

    // what do i do here? i got no clue

    throw new NotImplementedException();
}

I have tried experimenting with various examples online but nothing seems to work.

The idea is that web api would serve any range of files back to the front end, depending on whats on server.

File sizes range from 100kb to 50mb at this stage, file can be bigger once i implement archiving and zipping of multiple files.

2 Answers 2

5

If you want your API to return a file you can use this simple code:

[HttpGet("{id}")]
public IActionResult Get(Guid id)
{
    var bytes = System.IO.File.ReadAllBytes(@"YourFilePAth");

    return File(bytes, "application/octet-stream", "YourFileName.extension");
}
Sign up to request clarification or add additional context in comments.

3 Comments

How will this behave with large files? Because some files range from 100kb to 50 mb?
@Aeseir I've tested locally with files over 100MB without problems but I think it might depend on your server settings though.
Good enough, I went a bit further to streamline this to make it work properly.
2

It is wiser to use a stream:

[HttpGet("{id}")]
public IActionResult Get(Guid id)
{
    var stream = System.IO.File.OpenRead(@"YourFilePAth");

    return File(stream, "application/octet-stream", "YourFileName.extension");
}

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.