Get binary from uploaded file (image) in ASP.NET MVC - asp.net-mvc

I'm using the following code:
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
And...
[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Instead of saving the file to the filesystem, I want to extract the binary data from the incoming file so I can commit the image to my database. What changes can I make to my code to support this?

Perhaps try this snippet in your solution:
byte[] imgData;
using (BinaryReader reader = new BinaryReader(file.InputStream)) {
imgData = reader.ReadBytes(file.InputStream.Length);
}
//send byte array imgData to database, or use otherwise as required.

Related

Upload File in MVC and create a link to Download the the file

I have created this code for upload file. But it does not upload any file in the App_Data/Uploads folder i have created.
Here is the code>>
In view>>
<form action="~/Views/Home/_SaveUpdate" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
And this my Handler>>
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(HttpContext.Server.MapPath("~/App_Data/Uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
Please tell me what more needs to be done. Also, how to generate the Link to download the file.
First, the action of the form now points to ~/Views/Home/_SaveUpdate while this should be /Home/Index based on your post-Action.
Second, make sure that you have created an Upload folder inside your App_Data folder.
This should take care of the upload problem.
View:
<form action="/Home/Index" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
If you want to display download links to all uploaded files, you should store the images in a different folder than App_Data. The App_Data folder is not directly accessible due to security reasons.
A good example to show the files in a directory can be found here
I took your code and made just a few changes to test it.. and it worked.
For my tests i just changed the name of the action.
Are you sure your form Action is correct?
<form action="~/Views/Home/_SaveUpdate"
because it doesn't match with the name of your handler:
public ActionResult Index(IEnumerable ....
My test:
Make sure your Upload folder exist or you'll get an exception.
The Handler:
[HttpPost]
public ActionResult FileUploadPost(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(HttpContext.Server.MapPath("~/Uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
The View:
<form action="FileUploadPost" method="post" enctype="multipart/form-data">
<label for="file1">Filename1:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename2:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>

Uploading image using json in aps mvc

I have a function for uploading selected files into folder in asp mvc4. The code in view page is
<form id="form1" method="post" enctype="multipart/form-data" action="EmployeeDetails/Upload">
<input type='file' id="imgInp" accept="image/jpeg"/>
<p>
<input type="submit" value="Upload" class="btn"/>
</p>
</form>
And the controller code is
[HttpPost]
public ActionResult Upload(HttpPostedFileBase imgInp)
{
if (imgInp != null && imgInp.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(imgInp.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/images/Profile"), fileName);
imgInp.SaveAs(path);
}
return view("Index");
}
Instead of this i want to send the image from view to controller as Json. Or is there any other methods to upload image without refreshing the view page..?
You can send form using ajax...
<form id="login-form">
<input type="file" name="photo" id="files" accept="image/*;capture=camera">
<button type="submit" onclick="submitform()">Submit</button>
</form>
jquery
function submitform(){
var postdata = $('#login-form').serialize();
var file = document.getElementById('files').files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Home/Index", false);
xhr.send(fd);
}
controller
[HttpPost]
public JsonResult Index(FormCollection data)
{
if (Request.Files["files"] != null)
{
using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
{
var Imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//your image
}
}
}
uploading file to the server is quite simple. we need is a html form having encoding type set to multipart/form-data and a file input control.
View: NewProduct.cshtml
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>New Product</legend>
<div>
<label>Product Name:</label>
#Html.TextBoxFor(x => x.ProductName)
</div>
<div>
<label>Product Image:</label>
<input name="photo" id="photo" type="file">
</div>
<div>
#Html.ValidationSummary()
</div>
<input type="submit" value="Save" />
</fieldset>
</form>
The uploaded files are available in HttpFileCollectionBase of Request.Files.
controller:
[HttpPost]
public ActionResult NewProduct()
{
HttpPostedFileBase image = Request.Files["photo"];
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var fileName = Path.GetFileName(image.FileName);
string subPath = Server.MapPath("ProductLogo");
bool isExists = System.IO.Directory.Exists(subPath);
if (!isExists)
System.IO.Directory.CreateDirectory(subPath);
var path = Path.Combine(subPath+"\\", fileName);
if (System.IO.File.Exists(path))
{
var nfile = DateTime.Now.ToString() + "_" + fileName;
path = Path.Combine(subPath+"\\", nfile);
}
file.SaveAs(path);
return RedirectToAction("List", "Product");
}
else
{
ModelState.AddModelError("", "Please Select an image");
return View();
}
}
else
{
return View();
}
}

renaming file uploaded based on its input type's attribute(id) asp.net in mvc

View:
#using (Html.BeginForm("Edit","program","",FormMethod.Post,new {enctype = "multipart/form-data"}))
{
<div class="upload">
<input type="file" name="files" id="EpExpert"/>
<input type="file" name="files" id="EpNewbie"/>
<input type="submit" name="submit" value="submit" id="submit"/>
</div>
}
Controller:
[HttpPost]
public ActionResult Edit(tr_program program, IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file != null)
{
//string extension = Path.GetExtension(file.FileName);
string path = AppDomain.CurrentDomain.BaseDirectory + "Documents/Program-PDFs/";
string filename = Path.GetFileName(file.FileName);
file.SaveAs(Path.Combine(path, filename));
}
}
}
uploaded file name should be in file-{id}.pdf
eg: file-EpNewbie.pdf
file-EpExpert.pdf
PLEASE help!!
The id is never sent to the server. You could use the name attribute instead:
#using (Html.BeginForm("Edit", "program", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="upload">
<input type="file" name="EpExpert" />
<input type="file" name="EpNewbie" />
<input type="submit" name="submit" value="submit" id="submit"/>
</div>
}
and in your controller action:
[HttpPost]
public ActionResult Edit(tr_program program)
{
string location = Server.MapPath("~/Documents/Program-PDFs");
foreach (string name in Request.Files)
{
HttpPostedFileBase file = Request.Files[name];
string filename = string.Format("file-{0}.pdf", name);
filename = Path.Combine(location, filename);
file.SaveAs(filename);
}
...
}
Obviously since you are storing all the files in the same location (~/Documents/Program-PDFs) with the same names (file-EpExpert.pdf and file-EpNewbie.pdf) if 2 users upload different files at the same time they might get overwritten. There seems to be a problem with your design and naming convention but in my answer I illustrated how you could pass the name of the file input to the controller action which could be used to build the resulting filename. Now it's up to you to take this into consideration when building your real application.
You can take an idea from here. Firstly declare id and data-id dynamic. for example
id = '#model.Id' data-id = '#model.Id'
Before submit form, use js or jquery take id value, then post form.
$("#myForm").submit(function () {
var idValue = $(this).attr('data-id');
document.getElementById('yourHiddenValue').value = idValue;
});

How to get file from HDD to Bitmap object [ASP MVC 3]?

I'm new to ASP MVC and I've been trying to upload a bitmap file from hard drive to a C# Bitmap object, which I would later assign to my Model.
The view (cshtml file) looks like this:
<form action = "DisplayAddedPicture" method=post>
<input type=file name="Picture" id = "Picture"/>
<input type=submit value="Send!" />
</form>
And the DisplayAddedPicture method from controller:
[HttpPost]
public ActionResult DisplayAddedPicture()
{
HttpPostedFileBase File = Request.Files["Picture"];
if (File == null) throw new Exception("NullArgument :( ");
// file stream to byte[]
MemoryStream target = new MemoryStream();
File.InputStream.CopyTo(target);
byte[] TempByteArray = target.ToArray();
// byte[] to Bitmap
ImageConverter imageConverter = new ImageConverter();
Image TempImage = (Image)imageConverter.ConvertFrom(TempByteArray);
Bitmap FinalBitmap = new Bitmap(TempImage);
// (...)
}
It turns out that every time all I get is an Exception, as the HttpPostedFileBase object is always null. Is there any flow in my logic (apart from all of those conversions which come afterwards, I know they're messy) or is there any other way to solve this?
Try this
In your View,
#using (Html.BeginForm("DisplayAddedPicture", "YourControllerName",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type=file name="Picture" id = "Picture"/>
<input type=submit value="Send!" />
}
And the Action method
[HttpPost]
public ActionResult DisplayAddedPicture(HttpPostedFileBase Picture)
{
if (Picture!= null && Picture.ContentLength > 0)
{
//Do some thing with the Picture object
//try to save the file here now.
//After saving follow the PRG pattter (do a redirect)
//return RedirectToAction("Uploaded");
}
return View();
}
Try adding the following to your form tag: enctype="multipart/form-data"
<form method="post" action="DisplayAddedPicture" enctype="multipart/form-data">
<input type=file name="Picture" id = "Picture"/>
<input type=submit value="Send!" />
</form>

Pass extra parameters along with the HttpPostedFileBase object

In my MVC app, I have an upload View with GET and POST actions.
the question is how can I pass extra data to the POST Action along with the HttpPostedFileBase object, e.g., some ID for example.
You just pass it as an additional parameter
HTML:
<form action="" method="post" enctype="multipart/form-data">
<input type='text' id='txtId' name='id'/>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string id) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}

Resources