user2962142
user2962142

Reputation: 2066

image upload in asp.net razor website

i have a form where you enter information about the picture and upload it, the upload code in the html form is :

 @FileUpload.GetHtml(
                initialNumberOfFiles: 1,
                allowMoreFilesToBeAdded: false,
                includeFormTag: false,
                uploadText: "Upload"); 

and in the c# code in the same page i got :

                            var fileName = "";
                            var fileSavePath = "";
                            var uploadedFile = Request.Files[0];
                            fileName = Path.GetFileName(uploadedFile.FileName);
                            fileSavePath = Server.MapPath("~/Images/inscriptions/" +
                            fileName);
                            uploadedFile.SaveAs(fileSavePath);

for some reason i get the error "index out of range" on the line :

var uploadedFile = Request.Files[0];

i want the user to click browse choose the file and fill the other Text boxes and click save to upload the picture and fill the info in the database(which is handled)

Upvotes: 0

Views: 866

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

I figured out your problem may be solved with one of these solutions:

Solution 1: Change includeFormTag: false to includeFormTag: true.

@FileUpload.GetHtml(
            initialNumberOfFiles: 1,
            allowMoreFilesToBeAdded: false,
            includeFormTag: true,
            uploadText: "Upload");

This solution apply if FileUpload helper placed outside any form tag.

Solution 2: Use Html.BeginForm with attribute enctype="multipart/form-data" that wraps FileUpload helper.

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @FileUpload.GetHtml(
            initialNumberOfFiles: 1,
            allowMoreFilesToBeAdded: false,
            includeFormTag: false,
            uploadText: "Upload");
}

This solution apply if you don't want to create new form tag by FileUpload helper and use existing form instead.

NB: IndexOutOfRangeException on Request.Files[0] originated from form submission request which omitted file part contained in <input type="file" />, hence you need to include enctype="multipart/form-data" attribute (see explanation here).

Related problems:

How to use @FileUpload.GetHtml inside Html.BeginForm and sumbit FilesList

Trying to work with Request.Files in WebMatrix

Upvotes: 1

Related Questions