I have a model of Client with a property — public string PhotoPath {get; set;}.
I'm trying to add an image in Create httppost method:
public ActionResult FileUpload(HttpPostedFileBase file, Guid id)
{
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);
Client client = db.Clients.Find(id);
if (client == null) return HttpNotFound();
client.PhotoPath = path;
ViewBag.IMAGEPATH = path;
}
return RedirectToAction("Create");
}
There is a view (with buttons for adding):
#using (Html.BeginForm("FileUpload", "ClientsController", FormMethod.Post,
new { enctype = "multipart/form-data", id = Model.СlientIdentificator }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
But then I'm trying to upload an image there is no any result (image doesn't upload) or there is an exception targeted to id = Model.ClientIdentificator:
http://i.stack.imgur.com/zqA4y.png
As a result, I'm really want to ask you for universal method to upload an image for client, using controller's method with two arguments HttpPostedFile file and Guid cliendId or a method that is compatible for my task.
P.S. I'll be extremely thankful
P.P.S. Sorry for my English skills :3)
Related
I'm trying to upload a JSON file, but the MVC controller is always interpreting it as null.
View:
<h3>OR</h3><br>
#Html.TextBox("jsonFile", null, new { type = "file" })
<div class="col-md-offset-2 col-md-10 ">
<input type="submit" value="Create" class="btn btn-default submit-button" formaction="Create" />
</div>
Controller:
public ActionResult Create(HttpPostedFileBase jsonFile)
{
MessageBox.Show("Create");
String str;
if (ModelState.IsValid)
{
if (jsonFile != null)
{
MessageBox.Show("File Upload Success");
StreamReader jsonReader = new StreamReader(jsonFile.InputStream);
str = jsonReader.ReadLine();
MessageBox.Show(str);
}
else
{
MessageBox.Show("Null");
}
return RedirectToAction("Index");
}
return View(projectDetail);
}
Its the part of bigger program and I have used following code for form:
#using (Html.BeginForm( new { htmlAttributes = new { enctype = "multipart/form-data" } } ))
{
}
I get this button to upload files and file upload is also working well as I can see its uploaded status before I click Submit. Not sure why it's always null in the controller.
Have you decorated your action method with "HTTPPOST" attribute? I can't see that in your create action.
public ActionResult Create(HttpPostedFileBase jsonFile)
And also you have to update your form as blow to have controller and action method.
#using (Html.BeginForm("Create", "ControllerName", FormMethod.Post, new { id = "FormCreate", enctype = "multipart/form-data"}))
I try to user an input type file to upload a file but my code don't work.
the variable "filePosted" stay to null value.
My code :
HTML :
<form method="post" name="gestionmembre" runat="server" enctype="multipart/form-data">
#using (Html.BeginForm()){
<label class="lmembre" for="nom">Nom:</label>#Html.TextBox("nom")<br />
<label class="lmembre" for="prenom">Prénom:</label>#Html.TextBox("prenom", Request["Prenom"])<br />
<label class="lmembre" for="mail">Mail:</label>#Html.TextBox("mail", Request["mail"])<br />
<label class="lmembre" for="photo">Photo:</label><input id="phototelecharge" type="file" name="photo" value="Télécharger photo"/> <br />
<div class="errorform">#Html.ValidationSummary()</div>
<input id="ajoutmembre" type="submit" name="boutonmembre" value="Ajouter"/>
}
</form>
I don't know if I have to put this atributes in form tag (method runat enctype).
now, in the controler, in block to receive form values, I put :
else if (Request["boutonmembre"] == "Ajouter")
{
//Traitement de l'upload de l'image
HttpPostedFile filePosted;
filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];
if (filePosted != null && filePosted.ContentLength > 0)
{
string fileNameApplication = System.IO.Path.GetFileName(filePosted.FileName);
string fileExtensionApplication = System.IO.Path.GetExtension(fileNameApplication);
// generating a random guid for a new file at server for the uploaded file
string newFile = Guid.NewGuid().ToString() + fileExtensionApplication;
// getting a valid server path to save
string filePath = System.IO.Path.Combine(Server.MapPath("uploads"), newFile);
if (fileNameApplication != String.Empty)
{
filePosted.SaveAs(filePath);
}
}
}
The problem is in :
filePosted = System.Web.HttpContext.Current.Request.Files["phototelecharge"];
The variable fileposted is null.
In the webpage, I select a file fro a disk and the path of the file is realy indicate in the textbox.
Tks for help me.
David
Here is a simple example
Controller
namespace stackoverflow.Controllers
{
public class HomeController : Controller
{
public ActionResult PostFile(HttpPostedFileBase myFile)
{
System.Diagnostics.Debugger.Break();
return View();
}
}
}
View
#using (Html.BeginForm("PostFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div id="postdata">
<input type="file" name="myfile" id="myFile" />
<input type="submit" value="submit" />
</div>
}
This question already has answers here:
File Upload ASP.NET MVC 3.0
(23 answers)
Closed 9 years ago.
I'm posting a simple text file to an asp.net MVC app. When I post using the form below, the form parameter is not null. But file is. Any ideas what I'm doing wrong?
<form method=post action="http://localhost/Home/ProcessIt"
enctype="application/x-www-form-urlencoded">
<input type=file id="thefile" name="thefile" />
<input type="submit" name="Submit" />
</form>
In the asp.net mvc app:
[HttpPost]
public ActionResult ProcessIt(FormCollection thefile)
{
HttpPostedFileBase file = Request.Files["thefile"];
...
}
This works for me:
View:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
Controller:
[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);
// then save on the server...
var path = Path.Combine(Server.MapPath("~/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Index");
}
Need to change the enctype to multipart/form-data: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
Recently I am getting interested in image manipulation. But I am stuck just at the beginning of the long journey.
I have a problem in uploading an image in asp.net mvc3(razor view) project.
Can any one suggest me a basic sample/tutorial how to do it so.
To upload an image just call this in your html.
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Upload" />
}
Be sure to have enctype = "multipart/form-data" or your file won't be uploaded.
Then from the controller just handle the Request.Files of accept directly a HttpPostedFileBase
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//file handling logic
file.SaveAs(/* your path here */);
}
return RedirectToAction("Index");
}
Remember also that classic file upload don't work with ajax calls. If that is the case you must use a plugins like this one
I have a null object reference exception in executing this code. I have a file html control and my Razor code looks like this:
#using (Html.BeginForm("AddFiles", "AdministerFiles", FormMethod.Post))
{
<p><label for="filename">Filename : </label><input type="text" name="filename" /></p>
<p><label for="description">Description : </label><input type="text" name="description" /></p>
<p><input type="file" name="file" id="file" /> </p>
<p><input type="hidden" value="#Model[2]" name="catid"/></p>
<input type="submit" value="Upload Now!" />
<input type="reset" value="Reset" />
}
My AdministerFilesController is this:
[HttpPost]
public ActionResult AddFiles(HttpPostedFileBase file, int catid, string description)
{
// Verify that the user selected a file {
if (file != null && file.ContentLength > 0)
{
// extract only the filename
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);
}
RefDataLinks_mst fileDetails = new RefDataLinks_mst()
{
LastModified = new DateTime(2012,1,1),
CategoryID = catid,
DataFileName = Path.GetFileName(file.FileName),
DataTitle = "SAMPLETITLE",
DataID = ((new Random()).Next(100, 1000)),
DataFilePath = "Sample/Path",
Description = description,
UpdatedBy = "Arjel",
FileSize = file.ContentLength
};
bool b = ServiceReferenceHelper.AddFile(fileDetails);
// Redirect back to the index action to show the form once again
return Redirect("AddFiles?catid=" + catid); //both works
//return RedirectToAction("ViewDataFiles", new { catid = catid });
}
The data from catid and description are received but the file references to a null object. What could be the problem?
Uploads actually require you to specify the enctype attribute on the form. Here's an example of how to do that:
#using (Html.BeginForm("AddFiles", "AdministerFiles", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
...
}