pass img to controller in Razor - c#

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

Related

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

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;

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

I want to insert uploaded image in root directory images folder and its path to image column in database

how can i make an uploading image page via razor syntax (CSHTML) to simply upload file to /image root with increasing name like imgxxxyyy.jpg when the img part is fixed and xxx is the id of the inserting/updating product and yyy is the increasing number of image of that product and store the path to the imagpath column in my table ?
more i think about it and i research about it i get more confused .... please help me in this case .
It would be easier if you used Guids for filenames. So you could define a view model:
public class MyViewModel
{
[Required]
public HttpPostedFileBase File { get; set; }
}
a view containing a form where the user will be able to select a file to upload:
#model MyViewModel
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.LabelFor(x => x.File)
#Html.TextBoxFor(x => x.File, new { type = "file" })
#Html.ValidationMessageFor(x => x.File)
<button type="submit">Upload</button>
}
and finally a controller to show the form and process the upload:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (model.File != null && model.File.ContentLength > 0)
{
var imageFolder = Server.MapPath("~/image");
var ext = Path.GetExtension(model.File.FileName);
var file = Path.ChangeExtension(Guid.NewGuid().ToString(), ext);
var fullPath = Path.Combine(imageFolder, file);
model.File.SaveAs(fullPath);
// Save the full path of the uploaded file
// in the database. Obviously this code should be externalized
// into a repository but for the purposes of this example
// I have left it in the controller
var connString = ConfigurationManager.ConnectionStrings["MyDb"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "INSERT INTO images VALUES (#path)";
cmd.Parameters.AddWithValue("#path", fullPath);
cmd.ExecuteNonQuery();
}
}
return View(model);
}
}

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