I have two images show together when I'm trying to update one image nothing happened I want to be able to update one image and the second stay the same
Controller.cs
public ActionResult Edit(MainSections mainSections, HttpPostedFileBase file , HttpPostedFileBase file2)
{
if (ModelState.IsValid)
{
var mainInDb = db.MainSections.Find(mainSections.MainID);
if (file != null)
{
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/images/" + ImageName);
file.SaveAs(physicalPath);
mainInDb.Img = ImageName;
}
if (file != null)
{
string ImageName2 = System.IO.Path.GetFileName(file2.FileName);
string physicalPath2 = Server.MapPath("~/images/" + ImageName2);
file2.SaveAs(physicalPath2);
mainInDb.smallImg = ImageName2;
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mainSections);
}
Edit.cshtml
#using (Html.BeginForm("Edit", "MainSections", FormMethod.Post,
new { enctype = "multipart/form-data" }))
<input type="file" name="file" id="file" />
<input type="file" name="file2" id="file2" />
First, Peter B seems to be right and the second one should be if (file2 != null).
Second, as i see each file contain an image and each file has a unique id so you can access the Needed image in the Needed file using the file id, then you can change whatever you want and it would only affect one image.
(for example: In your view add a Javascript function that can make the changes you want...check this: https://stackoverflow.com/a/1297456/6653133)
Related
OK, so I am trying to make the move to MVC.
I have a Model, view and Controller made, but now I want to change the create functionality of the app.
I am working with uploads and I have this system generated code in my contoller.
Function Create(<Bind(Include:="Id,Course,Category,SubCategory,FileName,FileType,UploadedBy,DateUploaded")> ByVal acAsset As acAsset) As ActionResult
If ModelState.IsValid Then
db.Assets.Add(acAsset)
db.SaveChanges()
Return RedirectToAction("Index")
End If
Return View(acAsset)
End Function
Now I want to change this so that it will
Check for the existence of a folder for Course, Category and Sub category. If this folder is not there it must be created.
Upload the file select by a file selection box.
Post the files' name to the db.
The code is not necessarily the issue, I am jut not sure where I should put in the controller?
I have read this article but is not dealing with the DB post.
Thank you in advance.
You just add your code in controller that you want to hit on button click
Your Razor View Code
#using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
C# Code
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
return RedirectToAction("UploadDocument");
}
}
In your View
<input type="file" name="file">
In your Controller
public actionresult(HttpPostedFileBase file)
{
string filename = Path.GetFileName(file.FileName);
string contentType = file.ContentType;
using (Stream fs = file.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
}
}
//Data Context Code here
tableName.File= bytes;
db.add(tableName);
db.SaveChanges();
}
I'm currently using Entity Framework Code First approach for my asp.net MVC3(aspx syntax) project.
I have a model in my project called EmployeeModel
public class EmployeeModel
{
public string imageinfo;
public string fileinfo;
}
My DbContext is
public class ContextDB:DbContext
{
public DbSet<EmployeeModel> Employee { get; set; }
}
I would like to have a file browser for both fileinfo and imageinfo in my view to upload the files and images and the path of the files and images need to be stored in the database.
Can anyone please help?
Try using
.chtml
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Controller
public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
return View();
}
// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
}
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
Controller :
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null) // file here will have your posted file which you post from view
{
int byteCount = file.ContentLength; <---Your file Size or Length
byte[] yourfile = new byte[file.ContentLength];
file.InputStream.Read(yourfile , 0, file.ContentLength);
var doc1 = System.Text.UnicodeEncoding.Default.GetString(empfile);
// now doc1 will have your image in string format and you can save it to database.
}
}
View :
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
I have this code in my HomeController
[HttpPost]
public ActionResult NewRequest(int? id, FormCollection form, HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(uploadFile.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/Documents/Files"), fileName);
uploadFile.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
And my NewRequest view is this
#using (Html.BeginForm("NewRequest", "Controllers", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<input type="file" name="uploadFile" />
<input type="submit" value="Upload" />
}
The problem is that the uploaded file, .txt file f.x. is always null.
Your given code is fine. The only case I can think otherwise is you route config is probably not right.
I've tested with this config and it worked like a charm.
routes.MapRoute(
name: "NewRequest",
url: "Controllers/NewRequest",
defaults: new { controller = "Controllers", action = "NewRequest" }
);
My Model
partial class Company
{
... More Properties
public HttpPostedFileBase FilePicture { get; set; }
public byte[] Picture { get; set; }
}
My Controller
[HttpPost]
public ActionResult Edit(int id, Models.Company model)
{
if(model.FilePicture != null)
{
using(Stream inputStream = model.FilePicture.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if(memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
model.Picture = memoryStream.ToArray();
}
}
//EditDefault does the persisting
return this.EditDefault(id, model);
}
My View
#using (Html.BeginForm("Edit", currentController, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
//Clicks on the Picture and the Upload butten are forwarded to the file input tag
//readUrl sets the image as sone as the file changes
<input id="filePicture" type="file" name="filePicture" onchange="readURL(this);">
<button type="button" id="pictureUploadBtnPicture" onclick="$('#filePicture').click();"> Upload</button>
//ClearImg clears the img tag and resets the file input tag
<button type="button" id="pictureDeleteBtnPicture" onclick="clearimg(this);"> Delete</button>
...if Picture not null
...{
<img id="PicturePicture" src="data:image/png;base64,#System.Convert.ToBase64String(#Model.Picture.ToArray())">
<input type="hidden" value="#System.Convert.ToBase64String(#Model.Picture.ToArray())" name="Picture"> **added**
...}
...else ... Render empty Picture and set it per javascript
<input type="submit" value="Safe" class="btn btn-primary">
}
I have a Form which contains some properties like name, city,... and a byte[] which contains the data for a picture. The upload, show and delete are working. My problem now is that when I change something and I safe the site again, the Picture Property is null in the model, that I get in the Post Action. I guess there is something not working with the mapping.
Just to be clear I want the img mapped to the byte[].
Thx in advance for any help :)
Update:
Thx to Matt Tabor ;)
Added a hidden input field and now I get it in the controller.
Updated the View in case somebody needs it.
<img id="Picture" name="Picture" src="data:image/png;base64,#System.Convert.ToBase64String(#Model.Picture.ToArray())">
this property is not an input, when you submit this to the server it wont sumbit the image.
you would have to use something like a hidden input storing the byte array.
try adding this under your image tag
#Html.HiddenFor(m=>m.Picture)
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>