1

I am trying to create an application in which a user can upload .CSV files into an SQL database that I have created. I have become a little confused when it comes to actually getting the file path from the view and writing it into the database.

First off, here is the model that I'm working off:

    public class OutstandingCreditCsv
{
    [CsvColumn(FieldIndex = 1, CanBeNull = false)]
    public string PoNumber { get; set; }
    [CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
    public DateTime CreditInvoiceDate { get; set; }
    [CsvColumn(FieldIndex = 3)]
    public string CreditInvoiceNumber { get; set; }
    [CsvColumn(FieldIndex = 4, CanBeNull = false, OutputFormat = "C")]
    public decimal CreditInvoiceAmount { get; set; }
}

And here is the controller code so far:

        public ActionResult Index()
    {
        CsvFileDescription inputFileDescription = new CsvFileDescription
        {
            SeparatorChar = ',',
            FirstLineHasColumnNames = true
        };

        var context = new CsvContext();

        IEnumerable<OutstandingCreditCsv> csvList =
        context.Read<OutstandingCreditCsv>("C:/Users/BlahBlah/Desktop/CsvUploadTestFile.csv", inputFileDescription);

        foreach (OutstandingCreditCsv line in csvList)
        {

        }

        return View();
    }

There are two areas where I need a little guidance. I'm not sure how to pass the file from the view to the controller, lets say my view is something simple like this:

<form action="" method="POST" enctype="multipart/form-data">
<table style="margin-top: 150px;">
    <tr>
        <td>
            <label for="file">Filename:</label>
        </td>
        <td>
            <input type="file" name="file" id="file"/>
        </td>
        <td><input type="submit" value="Upload"/></td>
    </tr>
</table>
</form>

I'm also unsure how I would actually loop the csv data into my database. You can see the foreach loop in my controller is empty. Any help would be appreciated. Thanks!

8
  • I just reread your question. You are having trouble with the file posting from mvc. Give me a minute and I'll update my answer. Commented Jul 23, 2015 at 17:57
  • Thanks, I appreciate it Commented Jul 23, 2015 at 17:57
  • I have updated my answer. You may not need to do everything I was doing there but you'll at least be able to see how the file upload part of it is handled. Commented Jul 23, 2015 at 18:08
  • Looks good, thanks for your help! Commented Jul 23, 2015 at 18:27
  • The only part I am not completely understanding is how to actually populate the database table: foreach (var item in model) { item.PoNumber item.CreditInvoiceDate item.CreditInvoiceNumber item.CreditInvoiceAmount } Usually I would do cc.PoNumber = item.PoNumber, but that can't be done here Commented Jul 23, 2015 at 18:41

1 Answer 1

1

I am editing my post to answer the part of the question I missed. What you are doing here is uploading the csv file to a temporary location, reading it into an object then if you want you can delete the csv file out of the temporary location (not shown).

[HttpPost]
public JsonResult UploadValidationTable(HttpPostedFileBase csvFile)
{
    CsvFileDescription inputFileDescription = new CsvFileDescription
    {
         SeparatorChar = ',',
         FirstLineHasColumnNames = true
    };

    var cc = new CsvContext();
    string filePath = uploadFile(csvFile.InputStream);
    var model = cc.Read<OutstandingCreditCsv>(filePath, inputFileDescription);

    //if your csv has several rows convert it to a list of your model
    //var model = cc.Read<List<OutstandingCreditCsv>>(filePath, inputFileDescription);
   //then you can loop through and do the same as below
   /*foreach(var row in model)
   {
        var invoice = row.CreditInvoiceNumber;
   }*/

    try
    {
        //do what you need here, like save items to database
        var invoice = model.CreditInvoiceNumber;

        var invoiceTable = yourContext.yourTable
            .FirstOrDefault(x => x.yourTableID == passedInId);

       invoiceTable.CreditInvoiceNumber = model.CreditInvoiceNumber;
       yourContext.SaveChanges();
    }
    catch(LINQtoCSVException ex)
    {

    }

    return Json(model, "text/json");
}

private string uploadFile(Stream serverFileStream)
{
    string directory = "~/Content/CSVUploads";

    bool directoryExists = System.IO.Directory.Exists(Server.MapPath(directory));

    if (!directoryExists)
    {
        System.IO.Directory.CreateDirectory(Server.MapPath(directory));
    }

    string targetFolder = Server.MapPath(directory);
    string filename = Path.Combine(targetFolder, Guid.NewGuid().ToString() + ".csv");

    try
    {
        int length = 256; //todo: replace with actual length
        int bytesRead = 0;
        Byte[] buffer = new Byte[length];

        // write the required bytes
        using (FileStream fs = new FileStream(filename, FileMode.Create))
        {
            do
            {
                bytesRead = serverFileStream.Read(buffer, 0, length);
                fs.Write(buffer, 0, bytesRead);
            }
            while (bytesRead == length);
        }

        serverFileStream.Dispose();
        return filename;
    }
    catch (Exception ex)
    {
        return string.Empty;
    }
}
Sign up to request clarification or add additional context in comments.

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.