locked
No file return downloaded file on browse although web API return file RRS feed

  • Question

  • User696604810 posted

    I work on asp.net core 2.2 web API project with angular 7 .

    my issue on  when click on upload button File not download as attachment on browser  .

    when put break point on API and run angular app it hit break point and file name can see from API when pass it by angular 

    But Issue not file downloaded or returned

    I think  angular app issue so

    How to solve it to can download on file .on browser and downloaded to download folder as image

    my web API code and angular 7

    [HttpPost, DisableRequestSizeLimit]  
         public IActionResult Upload()  
         {  
             try  
             {  
                 var DisplayFileName = Request.Form.Files[0];  
                 string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";  
                 string Month = DateTime.Now.Month.ToString();  
                 string DirectoryCreate = myValue1 + "\\" + Month + "\\" + fileName;  
                 string exportPath = myValue2 + "\\" + Month + "\\" + fileName;  
                   
      
                   
                 if (!Directory.Exists(DirectoryCreate))  
                 {  
                     Directory.CreateDirectory(DirectoryCreate);  
               
                 }  
                
                 ExcelEx ex = new ExcelEx();  
                 if (DisplayFileName.Length > 0)  
                 {  
                     var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');  
                     var dbPath = Path.Combine(DirectoryCreate, fileName);  
                     //var dbPath = Path.Combine(folderName, fileName);  
                     using (var stream = new FileStream(dbPath, FileMode.Create))  
                     {  
                         Request.Form.Files[0].CopyTo(stream);  
                         stream.Flush();  
                         stream.Close();  
                     }  
                     GC.Collect();  
                     //ExcelEx ex = new ExcelEx();  
                     string error = "";  
                     int rowCount = 0;  
                     string inputTemplatePath = "";  
                      
                     var InputfilePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Attachement", "DeliveryGeneration_Input.xlsx");  
                     bool areIdentical = ex.CompareExcel(dbPath, InputfilePath, out rowCount, out error);  
                     if (areIdentical == true)  
                     {  
                         List<inputexcel> inputexcellist = new List<inputexcel>();  
                         inputexcellist = ex.Import(dbPath);  
                         List<string> mods = new List<string>();  
      
                         mods = inputexcellist.Select(x => x.ModuleName).Distinct().ToList();  
                         var OutputfilePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "Attachement", "DeliveryGeneration_Output.xlsx");  
                         System.IO.File.Copy(OutputfilePath, exportPath, true);  
                
                         SqlConnection con;  
                         foreach (var m in mods)  
                         {  
                             List<inputexcel> inputmodulelist = new List<inputexcel>();  
                             inputmodulelist = inputexcellist.Where(x => x.ModuleName == m).ToList();  
                             var dtimport = datatableConversion.ToDataTable(inputmodulelist);  
                              
      
      
                             con = new SqlConnection(strcon);  
                             SqlCommand cmd = new SqlCommand("sp_DeliveryGenerationExporter_Page", con);  
                             cmd.CommandTimeout = 999999;  
                             cmd.CommandType = CommandType.StoredProcedure;  
                             cmd.Parameters.AddWithValue("@ModuleList", dtimport);  
      
                             con.Open();  
                             DataSet ds = new DataSet();  
      
      
                             DataTable dtexport = new DataTable();  
                             dtexport.Load(cmd.ExecuteReader());  
      
                             ex.Export(dtexport, m, exportPath);  
      
                             con.Close();  
                              
                         }  
                         
                     }  
           
                     var memory2 = new MemoryStream();  
                     using (var stream = new FileStream(exportPath, FileMode.Open))  
                     {  
                         stream.CopyTo(memory2);  
                     }  
                     memory2.Position = 0;  
                   
                     return File(memory2, "text/plain", Path.GetFileName(exportPath));  
      
                 }  
                 else  
                 {  
                     return BadRequest();  
                 }  
             }  
             catch (Exception ex)  
             {  
                 return StatusCode(500, $"Internal server error: {ex}");  
             }  
         }  
    on Angular 7
    component.html
    <button type="button" class="btn btn-success" (click)="uploadFile(files)">Upload Filebutton> component.ts
    fileToUpload: File = null; public uploadFile = (files) => { const formData = new FormData(); formData.append('file', this.fileToUpload,this.fileToUpload.name); this.http.post('https://localhost:44396/api/ApprovalQuality/', formData) .subscribe(data =>{ }, error => { console.log(error); }); } handleFileInput(files: FileList) { if (files.length == 0) { return; } this.fileToUpload = files.item(0); console.log(this.fileToUpload) }

     test API return like that by post man give me 200 Status OK

    http://www.mediafire.com/view/t6gfu75jk8k1yqo/test_api.png/file

    but on browser no file download as result

    when connect angular 7 with API no file returned and downloaded

    http://www.mediafire.com/view/epxx1jo3imsvcgv/web_api_with_angular_7_connect.png/file

    so How to solve issue 

    Tuesday, November 24, 2020 11:10 AM

All replies

  • User753101303 posted

    Hi,

    If you expect a browser download dialog it is is done when the browser handles diretly the http request and its response. When using Ajax you need some additional code to handle the response fom your code for example using something such as https://stackblitz.com/edit/angular-blob-file-download

    If unsure about what happens start with F12 Network (and/or F12 Console) to see first if the http request works as expected.

    Tuesday, November 24, 2020 12:40 PM
  • User696604810 posted

    yes exactly this is what i need 

    but i expect download file without display link

    because i already have file 

    my result expected is downloaded file as action done when downloaded file

    meaning i need downloaded file as example without link display

    Tuesday, November 24, 2020 12:47 PM
  • User753101303 posted

    It could have no visible text or you could use display:none and call its click() method from your JavaScript code. Other programmatic options at https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax

    My personal preference is to just use a browser level http post request. The browser knows this is a download so the current window content is kept unchanged and it can process the download as usual without having to add additional code. i'm using Ajjax for a download file whe I really need to do something more than triggering a download dialog.

    Tuesday, November 24, 2020 1:09 PM
  • User475983607 posted

    IF you expect the browser to download the file then you misunderstand a few fundamentals.  I recommend building a test page where the action returns a known file.  Hard code the file path.  Use the test action to debug the Angular code.  One you get the Angular code working as expected then troubleshoot the action which also contains questionable logic. 

    Tuesday, November 24, 2020 1:59 PM
  • User696604810 posted

    I know issues on angular but what is the problem on angular must do to fix issue

    this is actually my question

    Tuesday, November 24, 2020 2:51 PM
  • User753101303 posted

    Or again https://medium.com/@radicalloop/download-file-using-ajax-in-angular-4-50109564bf17

    The createAndDownloadBlobFile function creates an hidden a link to trigger the download dialog. 

    Edit: I assumed this is your issue but you can still "as usual" use first F12 Network and/or F12 Console to make sure first you don't have any JavaScript error and the http query itself works fine and that you are just missing the response processing code.

    Tuesday, November 24, 2020 3:12 PM
  • User475983607 posted

    ahmedbarbary

    I know issues on angular but what is the problem on angular must do to fix issue

    this is actually my question

    For the second time!!! Create a test application to exercise the Angular application.  

    The Angular code makes the request.  The response is returned to the Angular code.  As far as I can tell, the code you've shared does not handle the file response.

    My best guess is you expect the browser to magically download the file when in fact the response is returned to the your Angular application.  You need Angular support not Web API.  Typically JavaScript code makes a standard windows.location = "the file url" to download the file.  

    I explained several time in your other threads on this subject to return the file URL not the file!!!!

    Tuesday, November 24, 2020 3:15 PM
  • User696604810 posted

    thanks for reply

    How can i  Create a test application to exercise the Angular application. 

    really i need to know that

    if possible can you tell me How to do that

    or any sources can you tell me 

    Tuesday, November 24, 2020 3:27 PM
  • User475983607 posted

    thanks for reply

    How can i  Create a test application to exercise the Angular application. 

    really i need to know that

    if possible can you tell me How to do that

    or any sources can you tell me 

    Seriously?  According to your code you already know how to return a file.  Simply create a test file in the expected format and return the test file.  

    return File(System.IO.File.OpenRead("Path to the file"), "text/plain", "testfile.txt");

    Tuesday, November 24, 2020 3:50 PM