1

I need to add an upload function. A component on the page that allows you to upload a file that has a list of movies and information about the movies then display it to screen (webpage) and save to a database.

The part I need help with is parsing the contents of the uploaded csv file and saving the data to a sql server database and displaying the list of contents to the screen. I have created the upload function already see below:

This is an ASP.NET MVC 4 movie application.

Below is what I have so far:

View:

@using (Html.BeginForm("Upload", "Movies", FormMethod.Post, new {enctype="multipart/form-data"}))
{
    <input type="file" name="File" id="File" />
    <input type="submit" name="Submit"  value="Upload" />
    <span>@ViewBag.Message</span>
}

Controller:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase File )
{
    // Verify that the user selected a file
    if (File != null && File.ContentLength > 0)
    {
        // extract only the filename
        var fileName = Path.GetFileName(File.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        File.SaveAs(path);
        ViewBag.Message = "File uploaded successfully";
    }

    // redirect back to the index action to show the form once again
    return RedirectToAction("Index");
}

Model (database):

public class Movie
{
    public int ID { get; set; }

    [Required]
    public string Title { get; set; }

    //[DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }

    [Required]
    public string Genre { get; set; }

    [Range(1,100)]
    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

    public bool IsCompleted { get; set; }

    [StringLength(5)]
    public string Rating { get; set; }

    public string EnterUrl { get; set; }

    //public HttpPostedFileBase Document { get; set; }
}

public class MovieDBContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}
poke
  • 369,085
  • 72
  • 557
  • 602
  • What isn't working? This isn't a site for people to write your code for you. What's the specific problem you're having and trying to solve? Perhaps try breaking the question down into smaller parts that are easier for someone to reproduce. – Justin Helgerson Jun 24 '14 at 02:01
  • 1
    To be clear I never asked for anybody to write code for me so not sure where u got that from so no need to be rude. The specific problem I am having is getting the file that I have already uploaded. Parsing the file data from the uploaded file for example (title, releasedate, rating..etc) then saving those contents tp the database and having it displayed to the webpage. I've searched and tried using streamreader but can't seem to figure it out. If you can direct or walk me through how to accomplish this task would be helpful. –  Jun 24 '14 at 03:09
  • My intent was not to come off as rude. The question is just rather large in its current form. Parsing a file, saving it to the database and displaying it crosses a lot of technologies. It's just not clear what you're asking. For example, why can't you save the file? Are you getting an error? If not, then what's the problem? Same thing for the other problems. What about each step isn't working? – Justin Helgerson Jun 24 '14 at 03:14
  • No worries. I am trying to learn asp.net mvc 4. So I want to add an upload function. Above I have the uploaded function working just fine. Now I am struggling now with how to then get that uploaded file and read the data from it. I am able to save the uploaded file to folder in my application. Now I would like to retrieve that uploaded file to read in /parse the contents like (title, releasedate, rating..etc) and have it displayed to screen and stored in database. –  Jun 24 '14 at 03:23
  • I've tried used streamreader to read the entire file and then Im not sure what to do after that. –  Jun 24 '14 at 03:30

2 Answers2

1

I solved my own problem.

So, what I did was removed the part in upload function where I was saving the file to a folder and used stream reader to read in the file into a array and split each line by a comma, created a new movie object and then save to database as shown below.

    public ActionResult Upload(HttpPostedFileBase File )
    {

        // Verify that the user selected a file
        if (File != null && File.ContentLength > 0)
        {

            StreamReader csvReader = new StreamReader(File.InputStream);
            {
                string inputLine = "";
                while ((inputLine = csvReader.ReadLine()) != null)
                {
                    string[] values = inputLine.Split(new Char[] { ',' });
                    Movie movie = new Movie();
                    movie.Title = values[0];
                    movie.ReleaseDate = DateTime.Parse(values[1]);
                    movie.Genre = values[2];
                    movie.Price = Decimal.Parse(values[3]);
                    db.Movies.Add(movie);
                    db.SaveChanges();
                }
                csvReader.Close();
              }
        }
       // redirect back to the index action to show the form once again
        return RedirectToAction("Index");
    } 
0

So you want to save the file data itself into the database?

If so, try a byte array (byte[]) for the data type in your model. I'm pretty sure that entity framework will store it as a varbinary(max).

So instead of:

//public HttpPostedFileBase Document { get; set; }

Set it to:

public byte[] Document { get; set; }

Then to get the HttpPostedFile to a byte array:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Then rebuild and try again. Remember to use the using statement.

Or are you asking something else?

  • Thanks I will go over this to see if that helps. Do you mind walking me through this? I believe I've tried something like similar but didn't get it to work quite well. I just want to parse the file data from the uploaded file for example (title, releasedate, rating..etc) then saving those contents to the database and have it displayed to the webpage. I've searched and tried using Streamreader to read in the entire file. I guess what I'm trying to say is if I can get an example or explanation of how to parse the contents I need and save to db and display it. –  Jun 24 '14 at 03:15
  • What type of file are you uploading? A .mov file? A .mp4 file? Each one will have its own way of saving that data and as a result, you'll need a different parser for each file type to gain that information. So it really depends on what type of files you'd like to handle. – Chris Chamberlain Jun 24 '14 at 22:07
  • im uploading a csv file –  Jun 26 '14 at 17:45
  • How simple is the CSV file? I'd look into a CSV reader of some kind. Or see this: http://stackoverflow.com/questions/1375410/very-simple-c-sharp-csv-reader – Chris Chamberlain Jun 26 '14 at 22:34
  • its very simple file. It just has a list of movies so (title, release date, and rating) for each movie. That's all –  Jun 27 '14 at 16:27