0

I have a very simple view that will prompt a user to select a JSON file and then parse it.

Here is the relevant code from the view...

@using (Html.BeginForm("AddSampleDataJSON", "Event"))
{
   <input type="file" name="GetJSONFile" /><br>
   <input type="submit" />
}

Here is the method from the controller:

  [HttpPost]
  public ActionResult AddSampleDataJSON(FormCollection form)
  {
        string path = ??
        using (StreamReader r = new StreamReader(path))
         {
            string json = r.ReadToEnd();
            List<Event> events = 
            JsonConvert.DeserializeObject<List<Event>>(json);
         }
         return View();
  }

The question then is how do I access the full path so I can send it to the StreamReader to eventually parse the JSON. I don't see it in the FormCollection object.

5
  • 2
    You cant for security reasons (a browser only sends the file name and does not expose a uses file system). You parameter needs to be HttpPostedFileBase GetJSONFile and it will be populated with the file contents. And you need to set the enctype = "multipart/form-data" attribute in the form tag Commented Jun 13, 2017 at 0:16
  • As a parameter going into the method? It comes in as null even after I added that attribute. And the file I'm choosing is indeed a JSON file. Commented Jun 13, 2017 at 0:27
  • Then you did not set it correctly. (and it makes no difference what type of file it is) Commented Jun 13, 2017 at 0:28
  • I had to match the name of the element in the view with the variable name. Now it works! Commented Jun 13, 2017 at 1:02
  • That is what my first comment stated :) Commented Jun 13, 2017 at 1:24

1 Answer 1

2

You won't be able to access the client path to the file. You'll only see the file name.

You should set the encoding to multipart/form-data in your view:

@using (Html.BeginForm("AddSampleDataJSON", "Event", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <input type="file" name="uploadedFile" /><br>
     <input type="submit" />
}

And in your controller change your input parameter to HttpPostedFileBase, with the parameter name being the same as the name parameter in the form:

[HttpPost]
public ActionResult AddSampleDataJSON(HttpPostedFileBase uploadedFile)
{
    using (StreamReader r = new StreamReader(uploadedFile.InputStream))
    {
        string json = r.ReadToEnd();
        List<Event> events = JsonConvert.DeserializeObject<List<Event>>(json);
    }

    return View();
}
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.