简体   繁体   中英

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 eg /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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM