c# - unable to convert uploaded image to byte array -
i trying convert uploaded image byte array can store in database table.
the code below used perform conversion image byte array:
public byte[] converttobytes(httppostedfilebase image) { binaryreader reader = new binaryreader(image.inputstream); var imagebytes = reader.readbytes((int)image.contentlength); return imagebytes; }
when place breakpoints on code see being returned imagebytes variable displays {byte[0]}.
the code shown below receiving actionresult in controller view using upload image (currently using file input select , upload image):
[httppost] public actionresult newsmanager(newsmanagerviewmodel model) { var newsmanagerrepository = new newsmanagerrepository(); var currentuser = user.identity.name; if (modelstate.isvalid) { httppostedfilebase file = request.files["imagedata"]; var fileisimage = file.isimage(); if (fileisimage) { model.author = currentuser; var newsuploaded = newsmanagerrepository.uploadnews(file, model); if (newsuploaded == 1) { return view(); } modelstate.addmodelerror("uploadfailed", "news item not uploaded"); return view(model); } modelstate.addmodelerror("filenotimage", "the file have uploaded not image"); return view(model); } return view(model); }
does have ideas why images converting not being converted byte array?
any suggestions appreciated, application mvc 5 , .net version 4.5.
the calling method code below:
public int uploadnews(httppostedfilebase file, newsmanagerviewmodel model) { model.bannerimage = converttobytes(file); var ndtms2utils = new ndtms2utilsentities(); var news = new news { title = model.title, author = model.author, bannerimage = model.bannerimage, datecreated = datetime.now, newscontent = model.newscontent }; ndtms2utils.news.add(news); int = ndtms2utils.savechanges(); if (i == 1) { return 1; } return 0; }
use convert method mentioned below:
public byte[] converttobytes(httppostedfilebase image) { return image.inputstream.streamtobytearray(); } public static byte[] streamtobytearray(this stream input) { input.position = 0; using (var ms = new memorystream()) { int length = system.convert.toint32(input.length); input.copyto(ms, length); return ms.toarray(); } }
Comments
Post a Comment