Question ASP.NET Core MVC Chrome Excel Upload Problem

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
362
Programming Experience
10+
Hi guys,

I have an ASP.NET Core MVC application. I am trying to upload an excel and in the controller, I am inserting these data into a database. It works on FF and IE but in Chrome it keeps waiting and waiting without an error. I checked the developer tool on chrome but no error. Any ideas why it is not working?

Screenshot

Here is the ImportExcel.cshtml

ImportExcel.cshtml:
    @{
        ViewData["Title"] = "ImportExcel";
    }
  
    <h2 class="font-weight-bolder">Import Games </h2>
    <!DOCTYPE html>
    <html lang="">
    <head>
        <meta name="viewport" content="width=device-width"/>
    
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css"/>
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>    
    </head>
    <body>
  
    <form method="post"
          asp-action="Upload"
          asp-controller="GameBanks"
          enctype="multipart/form-data">
        <div class="input-group">
            <div class="custom-file">
                <input type="file" class="custom-file-input" name="postedFile" id="postedFile" aria-describedby="inputGroupFileAddon04">
                <label class="custom-file-label" for="postedFile">Choose file</label>
            </div>
  
            <div class="input-group-append">
                <button class="btn btn-outline-secondary" type="submit" id="inputGroupFileAddon04">Upload</button>
            </div>
        </div>
    </form>
  
    @section scripts {
        <script>
            $(document).ready(function() {
                $('#postedFile').on('change',
                    function() {
                        //get the file name
                        var fileName = $(this).val();
                        //replace the "Choose a file" label
                        $(this).next('.custom-file-label').html(fileName);  
                    });
  
                $("#inputGroupFileAddon04").click(function() {
                    // disable button
                    $(this).prop("disabled", true);
                    // add spinner to button
                    $(this).html(
                        '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Importing...'
                    );
                });
            });
        </script>
    }
  
    </body>
  
    </html>
Here is controller portion:
Controller:
            [HttpGet]
            [Authorize]
            public IActionResult ImportExcel()
            {
                return View();
            }
  
            [HttpPost]
            [Authorize]
            public async Task<IActionResult> Upload(IFormFile postedFile)
            {
                if (postedFile == null || postedFile.Length == 0)
                {
                    return RedirectToAction("ImportExcel");
                }
  
                try
                {
                    var timestamp = DateTime.UtcNow;
                    //Get file
                    var newfile = new FileInfo(postedFile.FileName);
                    var fileExtension = newfile.Extension;
  
                    //Check if file is an Excel File
                    if (fileExtension.Contains(".xls"))
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            await postedFile.CopyToAsync(ms);
  
                            using (ExcelPackage package = new ExcelPackage(ms))
                            {
                                ExcelWorksheet workSheet = package.Workbook.Worksheets["Game"];
                                int totalRows = workSheet.Dimension.Rows;
  
                                List<GameBanks> customerList = new List<GameBanks>();

                                for (int i = 2; i <= totalRows; i++)
                                {
                                    customerList.Add(new GameBanks
                                    {
                                        ProductDescription = workSheet.Cells[i, 1].Value.ToString(),
                                        ProductCode = workSheet.Cells[i, 2].Value.ToString(),
                                        UnitPrice = Convert.ToDouble(workSheet.Cells[i, 3].Value),
                                        Quantity = Convert.ToInt16(workSheet.Cells[i, 4].Value),
                                        Version = workSheet.Cells[i, 5].Value.ToString(),
                                        Currency = workSheet.Cells[i, 6].Value.ToString(),
                                        TotalPrice = Convert.ToDouble(workSheet.Cells[i, 7].Value),
                                        Status = Convert.ToInt16(workSheet.Cells[i, 8].Value),
                                        Used = Convert.ToInt16(workSheet.Cells[i, 9].Value),
                                        RequestDateTime = DateTime.Now,
                                        Signature = User.Identity.Name
                                    });
                                    customerList[i - 2].coupons = new GameBankPin
                                    {
                                        expiryDate = Convert.ToDateTime(workSheet.Cells[i, 10].Value),
                                        Serial = workSheet.Cells[i, 11].Value.ToString(),
                                        Pin = workSheet.Cells[i, 12].Value.ToString()
                                    };
                                }
  
                                //NLOG
                                NLog(logger, User.Identity.Name, timestamp, totalRows - 1);
                                _context.GameBanks.AddRange(customerList);
                                //_context.GameBankPins.AddRange(pins);
                                await _context.SaveChangesAsync();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    logger2.Error(e.Message);
                    throw;
                }

                return RedirectToAction("Index");
            }
 
Last edited by a moderator:
Well, instead of just running your code, you could set a breakpoint on your controller and see if the controller action is being called, and then step through the action code to try to see what is causing things to hang.

As an aside, it looks like you are using something called ExcelPackage to do your .xls file access. Are you sure it is certified for use in a server environment. Even Microsoft's ACE drivers is specifically marked as not for use in a web server.

But yes, I agree. It is strange that IE and FF were successful, but Chrome is giving you issues.
 
If I change the code to this in the cshtml, it works! Why is that?

ImportExcel.cshtml:
<form method="post"
              asp-action="Upload"
              asp-controller="GameBanks"
              enctype="multipart/form-data">
            <p>Upload excel file using this form:</p>
            <input type="file" name="postedFile"  />
            <input type="submit" value="Upload" />
        </form>
 
Just skimming right now, but the change from button to input on line 7 seems to be the critical change.
 
form submit does the trick :)

Click Button:
 $("#inputGroupFileAddon04").click(function() {
                // disable button
                $(this).prop("disabled", true);
                // add spinner to button
                $(this).html(
                    '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Importing...'
                );
                $("form[name=test]").submit();
            });
 
Expect to see a lot more of this. I honestly think Google is doing this deliberately. It's not the first time they've released an update which caused havoc with ASP server files being served up to their dom. Their last update prevented cookies from being set in the browser. Microsoft are now proposing to set cookies in JS on their own documentation. Not forgetting to mention Microsoft bought their own JS stack, so I'd start using as much JS as possible where possible because they plan on making their JS stack a part of Asp down the road.

You're better off using <input> anyway, as <button> breaks on mac browsers, and I think it still does.
 

Latest posts

Back
Top Bottom