Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create download feature using ASP.NET Core 2.1 and React JS?

I'm using ASP.NET Core and React JS. I'm newbie to this both platforms. I have used Axios for requesting data and getting response from server. But I have not requested images or any kind of file from server. This time I'm working on Download feature where user will click on button and can download desired file which is of .png, .jpg, .pdf format. I'm not understanding how can server will send data? I read, I needed to send base64 data which is converted from blob format. But not understanding how to request data from client and how server will serve desired file. In DB, I have stored only address of file e.g. /images/img1.jpg. This file actually resides in wwwroot/images folder. I have used downloadjs for downloading which is working correctly but after downloading, that image is not readable as it does not have any content.

Please anyone help me to implement this feature.

like image 911
Rohit Sawai Avatar asked Nov 19 '25 14:11

Rohit Sawai


1 Answers

First you need API to download data something like this

  public async Task<IActionResult> Download(string filename)  
  {  
      if (filename == null)  
          return Content("filename not present");  

      var path = Path.Combine(  
                     Directory.GetCurrentDirectory(),  
                     "wwwroot", filename);  

      var memory = new MemoryStream();  
      using (var stream = new FileStream(path, FileMode.Open))  
      {  
          await stream.CopyToAsync(memory);  
      }  
      memory.Position = 0;  
      return File(memory, GetContentType(path), Path.GetFileName(path));  
  } 

private string GetContentType(string path)  
    {  
        var types = GetMimeTypes();  
        var ext = Path.GetExtension(path).ToLowerInvariant();  
        return types[ext];  
    }  

    private Dictionary<string, string> GetMimeTypes()  
    {  
        return new Dictionary<string, string>  
        {  
            {".txt", "text/plain"},  
            {".pdf", "application/pdf"},  
            {".doc", "application/vnd.ms-word"},  
            {".docx", "application/vnd.ms-word"},  
            {".xls", "application/vnd.ms-excel"},  
            {".xlsx", "application/vnd.openxmlformats  
officedocument.spreadsheetml.sheet"},  
                {".png", "image/png"},  
                {".jpg", "image/jpeg"},  
                {".jpeg", "image/jpeg"},  
                {".gif", "image/gif"},  
                {".csv", "text/csv"}  
            };  
        } 

Then download file like this

axios({
  url: 'your url',
  method: 'POST',       // Worked using POST or PUT. Prefer POST
  responseType: 'blob', // important
}).then((response) => {
  const url = window.URL.createObjectURL(new Blob([response.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', 'file.pdf');
  document.body.appendChild(link);
  link.click();
});

Ref link

like image 150
Tony Ngo Avatar answered Nov 21 '25 04:11

Tony Ngo