I want to upload image to the server, The below code is working properly when i run the the code locally on my system, but when i upload it to the server it gives error message - The model item passed into the dictionary is of type 'Login.Models.User', but this dictionary requires a model item of type 'System.Collection.Generic.IEnumerable'[Login.Models.User]'.Please help to solve this issue.
public ActionResult FileUpload(HttpPostedFileBase file, Login.Models.User model)
{
if(ModelState.IsValid)
{
try
{
var user=db.User.FirstOrDefault(c=>c.Userid==model.Userid);
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/images/profile/"), pic);
file.SaveAs(path);
user.imagepath = "http://sampleApp.com/images/profile/" + pic;
}
Catch(Exception ex)
{
ModelState.AddModelError("",ex.Message);
}
return View("ViewAdmin",model);
}
db.ObjectStateManager.ChangeObjectState(user,System.Data.EntityState.Modified);
db.SaveChanges();
return RedirectToAction("User");
}
View
#model Login.Models.User
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
Related
I'm trying to use IBM Watson visual recognition in a web application. I want to send the path of the photo uploaded by the client to a function or a controller so I can use it to build and get a result from visual recognition(build an object).
I managed to get the path like this(in internet explorer):
var input = document.getElementById("file");
var filepath1 = input.value;
I want to know how can i send the path to a controller or to a function in c#.
I also tried to build a form and add an action to the controller but the controller name didn't show up.
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input accept="image/*" title="Choose an image to upload" type="file" name="file" id="file" />
<input type="submit" />
</form>
ViewModel
public class MyViewModel
{
[Display(Name = "My File")]
public IFormFile File { get; set; }
}
View
#model MyViewModel
<form asp-action="Send" enctype="multipart/form-data">
<label asp-for="File">Filename:</label>
<input accept="image/*" title="Choose an image to upload" type="file" asp-for="File" />
<input type="submit" />
</form>
Controller
[HttpPost]
public async Task<IActionResult> Send([Bind("File")] MyViewModel myVM)
{
if (myVM.File?.Length > 0)
{
byte[] fileBytes;
using (var fileStream = myVM.File.OpenReadStream())
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
fileBytes = ms.ToArray();
}
var fileName = Path.GetFileName(myVM.File.FileName);
var fileMimeType = myVM.File.ContentType;
var fileContent = fileBytes;
//You have all the file attributes and content
}
}
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
var _Img = new ImageBusiness();
var imge = new ImgView { FileName = file.FileName, FileType = file.ContentType };
imge.FileData = new byte[file.ContentLength];
file.InputStream.Read(imge.FileData, 0, file.ContentLength);
_Img.AddImge(imge);
ViewBag.Result = true;
return View ();
}
catch(Exception)
{
ModelState.AddModelError("","An error accured while uploading Image, please try again.");
return View();
}
}
this my view
#using (Html.BeginForm("Upload", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary();
<input name="file" /><br />
<input type="submit" class="btn btn-small" value="Save Brochure" />
}
theres no bugs just on run time when uploading of an image doesnt give me broswer option to select a picture.help will be appreciated thanks
hello i think maybe you missing type file on your input
try something like
<input type="file" name="file" /><br />
<input type="submit" class="btn btn-small" value="Save Brochure" />
I want to upload a file in folder image.
I use ASP.NET with MVC4 and razor.
I have this in my View :
<div class="editor-label">
#Html.Label("Descriptif")
</div>
<div class="editor-field">
<input type="file" name="fDescriptif" />
#Html.ValidationMessageFor(model => model.fDescriptif)
</div>
[...]
<p>
<input type="submit" value="Create" />
</p>
In my controller :
[HttpPost]
public ActionResult Create(formation formation)
{
if (ModelState.IsValid)
{
db.formations.Add(formation);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(formation);
}
In my model :
public string fDescriptif { get; set; }
I have no idea what I must do to upload my file in my folder "image" and save just the name of my file in my database. When I validate my form it's my complete path who saved.
On your view make sure you have added enctype = "multipart/form-data" to your form tag, and then try like this:
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmID" }))
And you can Get your file in Controller Action AS:
[HttpPost]
public ActionResult Create(formation formation,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
// Get your File from file
}
return View(formation);
}
you can find many questions like this, even on SO many answers have been given for this topic.
Here are 2 of the links. you should find your answer in this links. and many more other answers are there for this on SO. just google it, and you will find them.
https://stackoverflow.com/a/5193851/1629650
https://stackoverflow.com/a/15680783/1629650
Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):
#using (Html.BeginForm("ACTION", "CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
#Html.TextBoxFor(m => m.File, new { #type = "file" })
AND IN CONTROLLER
[HttpPost]
public ActionResult ACTION(ViewModels.Model taskModel)
{
string path = #"D:\Projects\TestApps\uploadedDocs\";
if (taskModel.File != null) {
taskModel.File.SaveAs(path +taskModel.TaskTitle
+ taskModel.File.FileName);
newUserProject.DocumentTitle = taskModel.TaskTitle
+ taskModel.File.FileName;
newUserProject.DocumentPath = path + taskModel.File.FileName;
}
}
<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 your controller should be as below
[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");
}
Actually I want to send the image and the text in the textbox to the controller...
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.Label("UserName:") <input type="text" id="txtImg" name="txtImg" /><br /><br />
#Html.Label("Upload:")<input type="file" name="image" /><br/>
<div id="Preview">
Preview
</div>
<input class="btn btn-success btnUpload" type="submit" value="upload" />
}
and I am trying to retrieve them in the controller in the below way:
public ActionResult Upload(HttpPostedFileBase image,string txtImg)
but I am not getting the textbox value..Is anything wrong withe code?
I have my sample code like this.
Controller:
public ActionResult Upload()
{
BlobStorageServices _blobstorageservice = new BlobStorageServices();
CloudBlobContainer container = _blobstorageservice.GetCloudBlobContainer();
List<string> blobs = new List<string>();
//List<BlobModel> models = BlobManager.getBlobs();
foreach (var blobItem in container.ListBlobs())
{
blobs.Add(blobItem.Uri.ToString());
}
return View(blobs);
}
[HttpPost]
public ActionResult Upload(string txtImg,HttpPostedFileBase image)
{
if (image.ContentLength > 0)
{
BlobStorageServices _blobstorageservice = new BlobStorageServices();
CloudBlobContainer container = _blobstorageservice.GetCloudBlobContainer();
CloudBlockBlob blob = container.GetBlockBlobReference(image.FileName);
//BlobManager.insertBlobUri(new BlobImage { Uri = blob.Uri.ToString() });
// string text = model.Name;
BlobManager.insertBlobUri(new BlobModel {Name=txtImg,Uri=blob.Uri.ToString()});
blob.UploadFromStream(image.InputStream);
}
return RedirectToAction("Upload");
}
View
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.Label("UserName:") <input type="text" id="txtImg" name="txtImg" /><br /><br />
#Html.Label("Upload:")<input type="file" name="image" id="upload"/><br/>
<div id="Preview">
Preview<img id="blah" src="#" alt="your image" />
</div>
<input class="btn btn-success btnUpload" type="submit" value="upload" />
}
<table style="border:1">
#foreach (var item in Model)
{
<tr style="border:1">
<td><img src="#item" alt="image" class="img-responsive" width="100" height="100" /></td>
<td><button class="btn btn-primary Delete" id="#item" onclick="deleteImage('#item');">Delete</button></td>
<td><a class="btn btn-primary Download" href="#item" target="_blank">Download Image</a></td>
<td><button class="btn btn-primary Download" onclick="updateImage('#item');">UpdateImage</button></td>
</tr>
}
I am sending the blobs directly into the view , that is the problem basically..How to use a model to insert text,bloburl,image?
Visit Uploading/Displaying Images in MVC 4
This helped me alot for uploading images
In Terms of retrieving data from the View to controller a better way is to use a ViewModel like
public class ExampleViewModel
{
public string Image {get; set;}
public string Text {get; set;}
}
and your view would look something like
#model YourProject.Models.ExampleViewModel
#using (Html.BeginForm("ExampleController","Home",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(model => model.Text)
<input id="Image" type="file" name="Image" data-val="true" />
}
and the controller
public ActionResult ExampleController(ExampleViewModel model)
{
//Not sure how you wanted to get the image so I just put this in here
foreach (string file in Request.Files)
{
HttpPostedFileBase hpf=Request.Files[file] as HttpPostedFileBase;
if(hpf.ContentLengh==0)
continue;
string folderPath = Server.MapPath("~/yourFolderPath");
Directory.CreateDirectory(folderPath);
string savedFileName = Server.MapPath("~/yourFolderPath/" + hpf.FileName);
hpf.SaveAs(savedFileName);
model.Image="~/yourFolderPath/" + hpf.FileName;
}
//this variable is getting the text from the ViewModel
string text=model.Text;
}
Hope this helps :)
I'm trying to save files to a folder in my site, but I keep receiving an UnauthorizedAccessException error.
[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase image)
{
var img = Path.GetFileName(image.FileName);
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/Content/productImages/"),
System.IO.Path.GetFileName(image.FileName));
image.SaveAs(path);
product.ImageName = img;
}
// save the product
repository.SaveProduct(product);
// add a message to the viewbag
TempData["message"] = string.Format("{0} has been saved", product.Name);
// return the user to the list
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(product);
}
}
HERE IS THE VIEW
#using (Html.BeginForm("Edit", "Admin", FormMethod.Post,
new { enctype = "multipart/form-data" })) {
#Html.EditorForModel()
<div class="editor-label">Image</div>
<div class="editor-field">
#if (Model.ImageName == null) {
#:None
} else {
<img width="150" height="150"
src="#Url.Action("GetImage", "Product", new { Model.ProductID })" />
}
<div>Upload new image: <input type="file" name="image" id="image"/></div>
</div>
<input type="submit" value="Save" />
#Html.ActionLink("Cancel and return to List", "Index")
}
I'm receiving the error on the image.SaveAs(path); line
I can't see what exactly I'm doing wrong. Any help?
Looks like a permission problem
Change the Permissions on productImages folder so that ASP.NET can write to that.