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

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();

Related

Display image in front end in ASP.NET MVC

In ASP.NET MVC, the image path is stored in the database and server folder (image) but not displayed on the front.
Images are shown like this:
I was trying to display the image on the front in ASP.NET MVC.
I also attached the code of the controller and view to display the image using the Entity Framework model
In my controller method:
[HttpPost]
public ActionResult Create(Personaltable p, Personal u)
{
try
{
// TODO: Add insert logic here
string filename = Path.GetFileNameWithoutExtension(u.AttachPicture.FileName);
string extension = Path.GetExtension(u.AttachPicture.FileName);
filename = filename + DateTime.Now.ToString("yymmssfff") + extension;
u.ImagePath = "~/Image/" + filename;
filename = Path.Combine(Server.MapPath("~/Image/"), filename);
u.AttachPicture.SaveAs(filename);
using (PersonaltableEntities entity = new PersonaltableEntities())
{
var t = new Personaltable()//Make Variable of Table
{
AttachPicture=SaveToPhysicalLocation(u.AttachPicture),
LastPayCertificate = SaveToPhysicalLocation(u.LastPayCertificate)
};
db.Personaltables.Add(t);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch()
{}
}
private string SaveToPhysicalLocation(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
file.SaveAs(path);
return path;
}
return string.Empty;
}
This is the view Controller on which I only show the image uploaded by the user in a list form.
public ActionResult Index()
{
return View(db.Personaltables.ToList());
}
This is my view:
#foreach (var item in Model)
{
<tr> <td><img src="~/Image/" width="100",height="250"/></td></td>
}
You must write src="~/Image/#item.ImagePath"
#foreach (var item in Model)
{
<tr> <td><img src="~/Image/(????)" width="100",height="250"/></td></td>
}

return file application.pdf to browser via asp net mvc controller shows code instead of file

I have a pdf file in a database that I loaded in the controller and directly want to return via return File
return File(document.Data, document.ContentType);
Data is the bytearray with ~76000 bytes
ContentType is the application/pdf
When I want to view the result in webbrowser (either FF or Chrome) I get to see the pdf code instead of the pdf.
%PDF-1.4 %���� 1 0 obj <>stream x��� and so on
Would appreciate any help because it must be so simple, but I can't find it.
The return is placed in ActionResult Index and I need it to be loaded right at click on page (no new page with _blank)
It is the right data, because when I use f12 in chrome and click on network and the data I get to view the pdf as a whole
Edit1:
[HttpGet]
public ActionResult Index(int Id)
{
InitMvcApplicationMenu();
...
var document = WebApi.LoadDocument(DocumentGuid.Value);
var byteArray = document.Data;
if (byteArray == null)
{
return null;
}
Stream stream = new MemoryStream(byteArray);
if (document == null)
{
return View("NoDocument");
}
Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return File(stream, document.ContentType, "document.pdf");
}
This way I get an error no file was found. When I use it the way before with
return File(document.Data, document.ContentType);
I get the bytearray as view instead of a pdf, but the file is found
Edit 2:
public ActionResult Index(int Id)
{
InitMvcApplicationMenu();
var entity = WebApi.LoadItem(Id);
var DocumentGuid = entity.ReportDocumentGUID;
if (DocumentGuid == Guid.Empty)
{
return View("NoDocument");
}
var document = WebApi.LoadItem(DocumentGuid.Value);
if (document == null)
{
return View("NoStatusReportDocument");
}
var cd = new ContentDisposition
{
FileName = document.Name,
Inline = true
};
Response.Headers.Add("Content-Disposition", cd.ToString());
return File(document.Data, document.ContentType);
}
I have a Wrapper with multiple registertabs and want to show the pdf inside the tab when the document tab is selected.
This happens here:
my.onHashChanged = function (e) {
var feature = jHash.val('feature');
my.loadTab(feature);
}
my.loadTab = function (feature) {
if (feature) {
$("#tabstrip-content").html("Loading...");
applicationUIModule.loadPartialView(feature, "Index", { Id: $("#Id").val()}
, function (data) {
}
, null
, $("#tabstrip-content")
);
}
}
my.onTabSelect = function (e) {
var feature = $(e.item).data("feature");
applicationUIModule.updateHash("feature", feature);
}
This is what you have to do:
[HttpGet]
public IActionResult document(int id)
{
var byteArray = db.instances.Where(c => c.id == id).FirstOrDefault().document;
if (byteArray == null)
{
return null;
}
Stream stream = new MemoryStream(byteArray);
Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return File(stream, "application/pdf", "document.pdf");
}

ASP.NET MVC Controller causing page reload when uploading a Blob

When I send a Blob to a controller via ajax, saving the file in the controller causes a page refresh. If I don't save the file, it doesn't refresh. My code:
Update I spun up a new blank ASP.NET MVC 5 app, copied over the ajax code, and it still refreshes the page if I save file in controller.
controller:
public class PicUploadTestsController : Controller
{
public ActionResult StackOverflowSample()
{
return View();
}
[HttpPost]
public string UploadPic()
{
var length = Request.ContentLength;
var bytes = new byte[length];
Request.InputStream.Read(bytes, 0, length);
WebImage webImage = new WebImage(bytes);
var path = Path.Combine(Globals_mt.Instance.ServerRootPath, "Areas/SampleTests/Img/test.jpg");
//If I comment out the save, no reload happens
webImage.Save(path);
return "/Areas/SampleTests/Img/test.jpg";
}
}
typescript:
$(function () {
$('#blob-upload').change((e) => {
var input = <HTMLInputElement>e.target;
var file = input.files[0];
getBlob(file, (blob: Blob) => {
var xhr = new XMLHttpRequest();
xhr.open('post', '/SampleTests/PicUploadTests/UploadPic', true);
xhr.send(blob);
});
});
function getBlob(file: File, callback: Function) {
var filereader = new FileReader();
filereader.onloadend = () => {
var imageEl = new Image();
imageEl.onload = () => {
var width = imageEl.width;
var height = imageEl.height;
var canvasEl: HTMLCanvasElement = document.createElement('canvas');
var context: CanvasRenderingContext2D = canvasEl.getContext('2d');
canvasEl.width = width;
canvasEl.height = height;
context.drawImage(imageEl, 0, 0, width, height);
var blob: Blob = dataUrlToBlob(canvasEl.toDataURL(file.type));
callback(blob);
};
var result = filereader.result;
imageEl.src = result;
};
filereader.readAsDataURL(file);
}
function dataUrlToBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], { type: contentType });
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
});
razor view:
#using (Html.BeginForm())
{
<label>ajax blob to FileReceiver()</label>
<input type="file" id="blob-upload" />
}
This happens no matter what I've tried, including uploading the file directly, saving either the file or Blob using file.SaveAs(), wrapping the blob in FormData(), moving the save operation out of the controller to a class library, not having a form in the view, i.e. just having an <input type="file" /> directly on the page, etc etc.
I'm using ASP.NET MVC 5, Visual Studio 2015
Am I missing something simple here? I had this working properly once upon a time.
Note: The reason I'm uploading a blob is because in the real code, I'm sizing the image down to a thumbnail so that I don't have to upload a 6mb file to create a 75 x proportionalHeight image.
Turns out the issue was with Mads Kristenson's Browser Link extension for Visual Studio, I disabled that and the issue was resolved
You need to return false from your JavaScript so that the page doesn't refresh.
$('#blob-upload').change((e) => {
var input = <HTMLInputElement>e.target;
var file = input.files[0];
getBlob(file, (blob: Blob) => {
var xhr = new XMLHttpRequest();
xhr.open('post', '/SampleTests/PicUploadTests/UploadPic', true);
xhr.send(blob);
});
return false;
});

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

unable to upload multiple db images with asp.net mvc

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];
}
}
}

Categories

Resources