A
A
Andrey Kornev2013-12-10 18:07:30
ASP.NET
Andrey Kornev, 2013-12-10 18:07:30

How to properly implement file upload in Asp.net MVC?

I implement the functionality of the pressure of the text section on the site.
It works, but there is an attachment of pictures to the section. And if there are pictures, that's fine too. and without pictures does not want.
throws: Exception Details: System.NullReferenceException: Object reference does not point to an instance of an object.

public ActionResult Add(
            List<HttpPostedFileBase> FolderImages,
            .......
)
{
....
if (FolderImages.Count<HttpPostedFileBase>()>0)
{
        foreach(HttpPostedFileBase Image in FolderImages)
        {
                string Path = "/Uploads/"+ DateTime.Now.GetHashCode() + Image.FileName;
                .....
                .....
        }
}

And here it throws ...System.NullReferenceException: The object reference does not point to an object instance.
string Path = "/Uploads/"+ DateTime.Now.GetHashCode() + Image.FileName;
What to do?
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Kornev, 2013-12-15
@webkornevand

Solved the problem in the following way.

foreach (string file in Request.Files)
{
            HttpPostedFileBase Image = Request.Files[file] as HttpPostedFileBase;
             ........
}

Well also removed List<HttpPostedFileBase> FolderImagesfrom method arguments.

I
Ilya Glebov, 2013-12-14
@IljaGlebov

If NullReferenceException in this line
"string Path = "/Uploads/"+ DateTime.Now.GetHashCode() + Image.FileName;"
then apparently Image == null
A similar problem is described here MVC. HttpPostedFileBase is always null
In short - instead of

<input type="file" name="files[0]" id="files[0]" />
<input type="file" name="files[1]" id="files[1]" />

should be
<input type="file" name="files" id="file1" />
<input type="file" name="files" id="file2" />

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question