Read single cell values from httppostedfilebase Excel File - c#

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;

Related

Read Text file without copying to hard disk

I'm using Asp.Net Core 3.0 and I find myself in a situation where the client will pass text file(s) to my API, the API will then parse the text files into a data model using a function that I have created called ParseDataToModel(), and then store that data model into a database using Entity Framework. Since my code is parsing the files into a data model, I really don't need to copy it to the hard disk if it isn't necessary. I don't have a ton of knowledge when it comes to Streams, and I've googled quite a bit, but I was wondering if there is a way to retrieve the string data of the uploaded files without actually copying them to the hard drive? It seems like a needless extra step.... Below is my code for the file Upload and insertion into the database:
[HttpPost("upload"), DisableRequestSizeLimit]
public IActionResult Upload()
{
var filePaths = new List<string>();
foreach(var formFile in Request.Form.Files)
{
if(formFile.Length > 0)
{
var filePath = Path.GetTempFileName();
filePaths.Add(filePath);
using(var stream = new FileStream(filePath, FileMode.Create))
{
formFile.CopyTo(stream);
}
}
}
BaiFiles lastFile = null;
foreach(string s in filePaths)
{
string contents = System.IO.File.ReadAllText(s);
BaiFiles fileToCreate = ParseFileToModel(contents);
if (fileToCreate == null)
return BadRequest(ModelState);
var file = _fileRepository.GetFiles().Where(t => t.FileId == fileToCreate.FileId).FirstOrDefault();
if (file != null)
{
ModelState.AddModelError("", $"File with id {fileToCreate.FileId} already exists");
return StatusCode(422, ModelState);
}
if (!ModelState.IsValid)
return BadRequest();
if (!_fileRepository.CreateFile(fileToCreate))
{
ModelState.AddModelError("", $"Something went wrong saving file with id {fileToCreate.FileId}");
return StatusCode(500, ModelState);
}
lastFile = fileToCreate;
}
return CreatedAtRoute("GetFile", new { fileId = lastFile.FileId }, lastFile);
}
It would be nice to just hold all of the data in memory instead of copying them to the hard drive, just to turn around and open it to read the text.... I apologize if this isn't possible, or if this question has been asked before. I'm sure it has, and I just wasn't googling the correct keywords. Otherwise, I could be wrong and it is already doing exactly what I want - but System.IO.File.ReadAllText() makes me feel it's being copied to a temp directory somewhere.
After using John's answer below, here is the revised code for anyone interested:
[HttpPost("upload"), DisableRequestSizeLimit]
public IActionResult Upload()
{
var filePaths = new List<string>();
BaiFiles lastFile = null;
foreach (var formFile in Request.Form.Files)
{
if (formFile.Length > 0)
{
using (var stream = formFile.OpenReadStream())
{
using (var sr = new StreamReader(stream))
{
string contents = sr.ReadToEnd();
BaiFiles fileToCreate = ParseFileToModel(contents);
if (fileToCreate == null)
return BadRequest(ModelState);
var file = _fileRepository.GetFiles().Where(t => t.FileId == fileToCreate.FileId).FirstOrDefault();
if (file != null)
{
ModelState.AddModelError("", $"File with id {fileToCreate.FileId} already exists");
return StatusCode(422, ModelState);
}
if (!ModelState.IsValid)
return BadRequest();
if (!_fileRepository.CreateFile(fileToCreate))
{
ModelState.AddModelError("", $"Something went wrong saving file with id {fileToCreate.FileId}");
return StatusCode(500, ModelState);
}
lastFile = fileToCreate;
}
}
}
}
if(lastFile == null)
return NoContent();
else
return CreatedAtRoute("GetFile", new { fileId = lastFile.FileId }, lastFile);
}
System.IO.File.ReadAllText(filePath) is a convenience method. It essentially does this:
string text = null;
using (var stream = FileStream.OpenRead(filePath))
using (var reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}
FormFile implements an OpenReadStream method, so you can simply use this in place of stream in the above:
string text = null;
using (var stream = formFile.OpenReadStream())
using (var reader = new StreamReader(stream))
{
text = reader.ReadToEnd();
}

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

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

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