简体   繁体   中英

HttpPostedFileBase to byte array make exception

I am using mvc 4

i have this model : ViewModelOne

public HttpPostedFileBase passportImage { get; set; }

Also, I have this model: modelViewTWO

public byte[] passportImage { get; set; }

I have this View witch use ViewModelOne as a model

@Html.TextBoxFor(model => model.passportImage, new { placeholder = "Uploadt Your Passport", type = "file"})

I have this controller:

public string Register(ViewModelOne newT) {
modelViewTWO second = new modelViewTWO();
byte[] data;
            using (Stream inputStream = newT.passportImage.InputStream)
            {
                MemoryStream memoryStream = inputStream as MemoryStream;
                if (memoryStream == null)
                {
                    memoryStream = new MemoryStream();
                    inputStream.CopyTo(memoryStream);
                }
                data = memoryStream.ToArray();
            }
            second.passportImage = data;
}

I got this exception

Object reference not set to an instance of an object.

in this line

newT.passportImage.InputStream

Edit

I check that newT.passportImage and It is null. why?

You need to add the enctype attribute to the form tag so the data gets posted as well:

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" })) {

(setting the first two parameters to null will post the same action and controller the form is on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM