unable to upload multiple db images with asp.net mvc - c#

I am trying to upload several db images onto the SQL Server 2008R2. I am using ASP.NET MVC 3 in C#. What is happening is that I getting the images displayed but the problem is that the second image is being displayed as twice. So it is duplicate. I am not sure why the first image is not being displayed.
My SubProductCategory4 Table has the following columns (for simplicity sake)...
Column Names: Image1 and Image2 has DataTypes varbinary(MAX), another column Name: ImageMimeType has DataTypes varchar(50).
My Controller has the following code for Create method...
[HttpPost]
public ActionResult Create([Bind(Exclude = "SubProductCategoryFourID")] SubProductCategory4 Createsubcat4, IEnumerable<HttpPostedFileBase> files, FormCollection collection)
{
if (ModelState.IsValid)
{
foreach (string inputTagName in Request.Files)
{
if (Request.Files.Count > 0) // tried Files.Count > 1 did
// not solve the problem
{
Createsubcat4.Image1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
Createsubcat4.Image2 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
// var fileName = Path.GetFileName(inputTagName);
//var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
}
// moved db.AddToSubProductCategory4(Createsubcat4);
// here but did not solve the problem
}
db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
return RedirectToAction("/");
}
//someother code
return View(Createsubcat4);
}
GetImage method...
public FileResult GetImage(int id)
{
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
MemoryStream streaml;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if ((z != null && z.Image1 != null) && (z != null && z.Image2 != null))
{
stream = new MemoryStream(z.Image1);
streaml = new MemoryStream(z.Image2);
}
else
{
var path = Server.MapPath(alternativePicturePath);
foreach (byte item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file.ContentLength == 0)
{
continue;
}
}
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
/* streaml = new MemoryStream();
var imagey = new System.Drawing.Bitmap(path);
imagey.Save(streaml, System.Drawing.Imaging.ImageFormat.Jpeg);
streaml.Seek(0, SeekOrigin.Begin);*/
}
return new FileStreamResult(stream,"image/jpg");
}
FileHandler.cs
public class FileHandler
{
public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
{
int nFileLen = file.ContentLength;
byte[] result = new byte[nFileLen];
file.InputStream.Read(result, 0, nFileLen);
return result;
}
}
create.cshtml...
#using (Html.BeginForm("Create", "ProductCategoryL4", "GetImage",
FormMethod.Post, new { enctype = "multipart/form-data" }))
//some code then...
<div class="editor-field">
#Html.EditorFor(model => model.Image1)
<input type="file" id="fileUpload1" name="fileUpload1" size="23"/>
#Html.ValidationMessageFor(model => model.Image1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Image2)
<input type="file" id="fileUpload2" name="fileUpload2" size="23"/>
#Html.ValidationMessageFor(model => model.Image2)
</div>
index.cshtml...
<img src="#Url.Action("GetImage", "ProductCategoryL4", new { id =
item.SubProductCategoryFourID })" alt="" height="100" width="100" />
</td>
<td>
<img src="#Url.Action("GetImage", "ProductCategoryL4", new { id =
item.SubProductCategoryFourID })" alt="" height="100" width="100" />
</td>
I am using using VS2010, ASP.NET MVC3 in C# with SQL Server 2008R2. Thanks in advance but please only respond if you know the answer. If there is a better way of doing this please let me know.

The code that is listed is looping through the files, and for each one, setting both Image1 and Image2 to be the same thing. When you upload 2 files, they are both showing up as image 2 because that was the last image applied to both fields.
Try replacing the loop with something more like this, which sets the fields one at a time if there are enough images.
FileHandler fh = new FileHandler();
if (Request.Files.Count > 0)
{
Createsubcat4.Image1 = fh.uploadedFileToByteArray(Request.Files[0]);
}
if (Request.Files.Count > 1)
{
Createsubcat4.Image2 = fh.uploadedFileToByteArray(Request.Files[1]);
}
db.AddToSubProductCategory4(Createsubcat4);
If you need to open this up to allow more images in the future, you'll want to replace the Image1 and Image2 fields with a collection of images, and use your loop again to add each image in the uploaded files collection. Something like this:
FileHandler fh = new FileHandler();
foreach (HttpPostedFileBase uploadedImage in Request.Files)
{
Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));
}
db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
EDIT:
Now that you are saving the images correctly, you need to take a second look at your GetImage action. You'll notice that you correctly load both files into memory, however when you specify your action result (return new FileStreamResult(stream,"image/jpg");) you are only ever returning the first stream. You need a way to return the second stream when requested. There are a couple ways to go about this, add another input parameter to specify which image to load or create a second action that only returns the second one.
To create the two action set up, your code would look something like this:
public ActionResult GetImage1(int id)
{
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if (z != null && z.Image1 != null)
{
stream = new MemoryStream(z.Image1);
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
public ActionResult GetImage2(int id)
{
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if (z != null && z.Image2 != null) // the difference is here
{
stream = new MemoryStream(z.Image2); // the difference is also here
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
These functions are almost identical and can easily be made 1 which takes a parameter to select which image to load.
public ActionResult GetImage(int id, int? imageNum)
{
imageNum = imageNum ?? 0;
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
byte[] imageData = null;
if (z != null)
{
imageData = imageNum == 1 ? z.Image1 : imageNum == 2 ? z.Image2 : null;
}
if (imageData != null)
{
stream = new MemoryStream(imageData);
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
This function would specify the imageNum as a query parameter like:
http://www.mydomain.com/controllerName/GetImage/{id}?imageNum={imageNum}

I think your problem might be in this loop.
foreach (string inputTagName in Request.Files)
{
if (Request.Files.Count > 0)
{
Createsubcat4.Image1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
Createsubcat4.Image2 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
// var fileName = Path.GetFileName(inputTagName);
//var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
}
}
db.AddToSubProductCategory4(Createsubcat4);
The Request.Files.Count > 0 should always be true since you are iterating through a list of Files. However, the real issue is that with this loop you overwrite the properties of Createsubcat4 with each file, and then after the properties are set with the last file, that is what gets sent to the database.
If you are trying to add multiple records into the database (one for each image), you'll need to move the AddToSubProductCategory4 within the loop. If you are trying to add two images to just that record, I'd recommend assigning each by name, and skipping the foreach loop.

public JsonResult Update(ProductViewModel model, HttpPostedFileBase imgpath1, IEnumerable<HttpPostedFileBase> imgpath2)
{
if (imgpath1 != null)
{
foreach (HttpPostedFileBase postedFile in imgpath1)
{
// var prodimage = Request.Files[i];
}
}
if (imgpath2 != null)
{
foreach (HttpPostedFileBase postedFile in imgpath2)
{
var prodimage = Request.Files[i];
}
}
}

Related

asp.net check image resolution and save in DB

asp.net core MVC - framework net6.0
I have a page in which i upload an image and save it to the db.
the file i'm getting from the view is IFormFile.
I want to be able to check the resolution (width and height) of the photo before saving in DB.
Can it be done with IFormFile?
here is the controller that handles the file :
public JsonResult Submit(IFormFile PhotoFile)
{
int success = 0;
string excep = "";
try
{
if (PhotoFile.Length > 0)
{
using (var ms = new MemoryStream())
{
PhotoFile.CopyTo(ms);
var fileBytes = ms.ToArray();
}
}
ApplicationUser appUser =
_unitOfWork.ApplicationUser.GetAll().Where(a => a.UserName == User.Identity.Name).FirstOrDefault();
if (appUser != null)
{
FileUpload fileUpload = new FileUpload()
{
file = PhotoFile,
CompanyId = appUser.CompanyId
};
SaveFile(fileUpload);
}
excep = "success";
success = 1;
return Json(new { excep, success });
}
catch (Exception ex)
{
excep = "fail";
success = 0;
return Json(new { excep, success });
}
}
public string SaveFile(FileUpload fileObj)
{
Company company = _unitOfWork.Company.GetAll().
Where(a => a.Id == fileObj.CompanyId).FirstOrDefault();
if(company != null && fileObj.file.Length > 0)
{
using (var ms = new MemoryStream())
{
fileObj.file.CopyTo(ms);
var fileBytes = ms.ToArray();
company.PhotoAd = fileBytes;
_unitOfWork.Company.Update(company);
_unitOfWork.Save();
return "Saved";
}
}
return "Failed";
}
As far as I know this isn't possible with just IFormFile and you need System.Drawing.Common.
So first you need to convert it like:
using var image = Image.FromStream(PhotoFile.OpenReadStream());
Then you can simply get the height/width with image.height and image.width

Get size of uploading file C# MVC

I'am trying create some validation for file size. My code:
[HttpPost]
public ActionResult Index(FotoModel model)
{
TryUpdateModel(model);
if (ModelState.IsValid)
{
if (model != null && model.File != null)
{
var fileName = Path.GetFileName(model.File.FileName);
var fileExtension = Path.GetExtension(fileName);
long fileSize = new FileInfo(fileName).Length;
fileName = "file" + fileExtension;
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
if (fileSize < 55000)
{
model.File.SaveAs(path);
model.link = fileName.ToString();
}
else
{
ViewData["Size"] = "Akceptowane pliki: jpg, jpeg, png o maksymalnym rozmiarze 50 KB";
}
return View(model);
}
}
return View(model);
}
And in this line:
long fileSize = new FileInfo(fileName).Length;
I'am receiving error: "File cannot be found". Do You know how can I resolved this ?
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
public ActionResult Index(FotoModel model, HttpPostedFileBase file)
{
if (file != null)
{
int byteCount = file.ContentLength; // <---Your file Size or Length
.............
.............
}
}
What you are looking is a ContentLength
public ActionResult Index(FotoModel model)
{
if (model != null && model.File != null)
{
var fileSize = model.File.ContentLength;
}
}

Read single cell values from httppostedfilebase Excel File

I have an Excelfile that the client send to server as httppostedfilebase and I need to know how I can read values from this file.
[HttpPost]
public ActionResult ShowExcelFile(GetExcel model)
{
var file = model.Files[0];
FileInfo info = new FileInfo(file.FileName);
var fileName = Path.GetFullPath(file.FileName);
if (file != null && file.ContentLength > 0)
{
using (ExcelPackage package = new ExcelPackage(info))
{
//Read some cell value, how?
}
}
return View("ShowExcelFile");
}
My model:
public class GetExcel
{
public List<HttpPostedFileBase> Files { get; set; }
public GetExcel()
{
Files = new List<HttpPostedFileBase>();
}
}
My view:
#using (Html.BeginForm("ShowExcelFile", "ShowExcel", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(m => m.Files, new { type = "file", name = "Files" })<br />
<input type="submit" value="Upload file" />
}
I really don't now how to do this, I have tried Excel Data Reader but it can't read formula values. I just wan't to read a cell value from this excelfile send from the client
Lets put this inside your controller action u will get the file:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult ShowExcelFile()
{
// For getting the file that is Uploadeded.
HttpPostedFileBase fileUpload = Request.Files["Files"];
byte[] data;
using (Stream inputStream = fileUpload.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
data = memoryStream.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
return Json(new { }, JsonRequestBehavior.AllowGet);
}
As far as I understand you use EPPlus library. To get the value you need to write smth like that
public void Upload(HttpPostedFileBase file)
{
package.Load(file.InputStream);
var worksheet = package.Workbook.Worksheets.First();
var cellValue = worksheet.Cells[rowIndex, columnIndex].Value;
var formulaValue = worksheet.Cells[rowIndex, columnIndex].Formula;
}
There are a few prolems with the how the controller and view are implemented . For example, your ActionResult expects List<HttpPostedFileBase>, but the view is posting HttpPostedFileBase.
However, beyond that, inside using of package, try:
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
worksheet.Select(new ExcelAddress("A1")); //there is more than one way to set this
string cellVal = (string)worksheet.SelectedRange.Value;

pass img to controller in Razor

I'm working on an ASP.net MVC4 application and I want to send an Image that I have on my view to the controller through a form
Here is my View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
<img src="img/annonceBrute.JPG" width ="60" height="60" name ="imageFile" />
#Html.TextArea("resultText")
<input type="submit" style="margin-left:40px;cursor:pointer;" id="l" value="Envoyer"/>
}
And in my controller I have a code that works with uploaded image but I want to use an image that already exists in my view. Here is the code of the controller
public ActionResult Index(HttpPostedFileBase imageFile)
{
var db = new Bd_scanitEntities();
IEnumerable<SelectListItem> items = db.JournalSet
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.label
});
ViewBag.IdJournal1 = items;
//Conversion
if (imageFile!= null && imageFile.ContentLength > 0)
{
// for now just fail hard if there's any error however in a propper app I would expect a full demo.
using (var engine = new TesseractEngine(Server.MapPath(#"./tessdata"), "eng", EngineMode.Default))
{
// have to load Pix via a bitmap since Pix doesn't support loading a stream.
using (var image = new System.Drawing.Bitmap(imageFile.InputStream))
{
using (var pix = PixConverter.ToPix(image))
{
using (var page = engine.Process(pix))
{
//meanConfidenceLabel.InnerText = String.Format("{0:P}", page.GetMeanConfidence());
//ViewBag.meanConfidenceLabel = String.Format("{0:P}", page.GetMeanConfidence());
ViewBag.resultText = page.GetText();
}
}
}
}
}
return View();
}
My problem is that I don't know which type I should use in the index argument in order to get the image from the view .
You can't send image to controller this way, if you only need the path of the image on controller, use hidden field:
<input type="hidden" name="image" value="img/annonceBrute.JPG"/>
if you want the whole image to be posted on server, you need to use input type file you can't post a html display tag to server using form, in form only input fields are posted on server.
in controller action you can read file like this:
public ActionResult MyAction(FormCollection form)
{
string filePath = Server.MapPath(form["image"].ToString());
byte[] buffer; //file bytes
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
try
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading
}
finally
{
fileStream.Close();
}
return View();
}
As it looks that you wants to upload image from view and Get HttpPostedFileBase in controller so use input file tag
<input id="image1" name="image1" type="file" />
in Controller action you should get HttpPosted file like this
if (Request.Files.Count > 0)
{
if (Request.Files["image1"].ContentLength > 0)
{
HttpPostedFileBase pf = Request.Files["image1"]
}
}
Now you can save this HttpPostedFileBase or what ever is your requirement

C# (Asp.net MVC 2) Display image from byte[] in View

I need to save picture in my datebase of asp.net mvc application. I created a field in a table MimeType (nvarchar[50]) and ImageData for save the picture in byte[]. I use ado.net. I save the image in a table like this:
private DBAppl db = new DBAppl();
public void CreateNewCar(newcar Car, HttpPostedFileBase image)
{
if (image != null)
{
Car.mimetype = image.ContentType;
Car.ImageData = new byte[image.ContentLength];
image.InputStream.Read(Car.ImageData, 0, image.ContentLength);
}
db.AddTonewcars(Car);
db.SaveChanges();
}
Picture normal saved in table. Then I walt to display my image in View. I create method in controller
public FileContentResult GetImage(int newcarid)
{
DBAppl db = new DBAppl();
newcar car = (from p in db.newcars
where p.newcarid == newcarid
select p).First();
return File(car.ImageData, car.mimetype.Trim());
}
In view I inserted this code:
<% if (Model.ImageData == null)
{ %>
None
<% }
else
{ %>
<img src="<%= Url.Action("GetImage", "Cars", new { Model.newcarid }) %>" alt="<%: Model.description %>" /> <% } %>
But the picture is not loaded, only alt. Help, what I done wrong? I try to use link in sourse code of html-page but a read that picture have error. I looked in mozilla "Information about the page" and see that page have my picture (778 kb) but it is 0px x 0px.
Try to set headers before returning file
HttpContext.Response.AddHeader("Content-Length"("Content-Type", "image/jpeg"));
or however you are accessing your headers.
use image/jpeg for jpg files
google for other extensions and file tpes.
I solved the problem this way:
public FileContentResult GetImage(int newcarid)
{
DBAppl db = new DBAppl();
newcar car = (from p in db.newcars
where p.newcarid == newcarid
select p).First();
return File(car.ImageData**.ToArray()**, car.mimetype.Trim());
}
In class:
public void CreateNewCar(newcar Car, HttpPostedFileBase image)
{
**var car = new newcar();**
if (image != null)
{
car.name = Car.name;
car.date = DateTime.Now;
car.color = Car.color;
car.picmimetype = image.ContentType;
int length = image.ContentLength;
byte[] buffer = new byte[length];
image.InputStream.Read(buffer, 0, length);
car.ImageData = buffer;
}
db.AddTonewcars(car);
db.SaveChanges();

Categories

Resources