Reputation: 147
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.
Upvotes: 0
Views: 890
Reputation: 147
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();
Upvotes: 0
Reputation: 13756
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.
Upvotes: 1