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
Related
I want to create a register form using MVC which include a profile photo. I don't want to add record for people before completing the form (including profile photo upload). Also I want my UploadImage view and controller to be re-usable for many forms (not just this form). I pass three variables to my upload form through ActionLink: RedirectAction (RA), RedirectController (RC), and dataname and the procedure goes like this:
I store RA, RC, dataname in ViewBag, then put them in hidden <input> tags to be submitted when POSTing the file
// GET: UploadImage/Upload
public ActionResult Upload(string RA, string RC, string dataname)
{
ViewBag.RedirectAction = RA;
ViewBag.RedirectController = RC;
ViewBag.DataName = dataname;
return View();
}
Put these lines in my Upload.cshtml (View):
#using (Html.BeginForm("Upload", "UploadImage", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="hidden" name="RA" value="#ViewBag.RedirectAction" />
<input type="hidden" name="RC" value="#ViewBag.RedirectController" />
<input type="hidden" name="dataname" value="#ViewBag.DataName" />
<input type="submit" name="Submit" id="Submit" value="Upload" />
}
Store the filename in TempData with dataname as the Key and redirect to /RC/RA:
// POST: UploadImage/Upload/
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string RA , string RC , string dataname)
{
var filepath = "C:/myfilename.jpg";
TempData.Add(dataname, filepath);
return RedirectToAction(RA,RC);
}
And get my filepath by utilizing TempData in my register form:
#if (TempData.Keys.Contains("MyData")) {
<div class="form-group">
<p>#TempData["MyData"].ToString()</p>
</div>}
The code works just fine, but the essential caveat is that I don't want other completed fields to get lost when redirected to the register form. How can I solve this problem ?
One option is to stick the data in the session. Another option would be to use a separate database table to hold in-progress registration data.
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)
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
I am using MVC 4 and I tried for upload file concept.
Here is my code:
<div class="complianceSubDiv">
<div class="complianceLeftDiv">
#Html.Label("Upload the file")
</div>
<div class="complianceRightDiv">
<input type="file" id="file" name="file" />
</div>
</div>
My controller code like
[HttpPost]
public ActionResult ManageDocument(DocumentModel documentModel, HttpPostedFileBase file)
{
//some code
}
But the HttpPostedFileBase file always returns null. I have searched more answers in StackOverflow and other websites and I got the working answer is parameter of HttpPostedFileBase variable name and fileupload control name are same . So I put the same name on all sides, but it returns null only.
Anyone help to me?
Finally i got it
Now i replaced for #using (Html.BeginForm())
to
#using (Html.BeginForm("ManageDocument", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
It's working !
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase myFile)
{
myFile = Request.Files["file"];
if (myFile != null && myFile.ContentLength > 0)
{
// your code ....
}
return View();
}
You can use "Request.Files" to get the selected file, above is the code.
In ASP.NET MVC4, a file-upload view is always sending null to the controller.
I have no idea why, I don't know how to fix it and searching has proven unfruitful...
Controller method:
[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase file)
{}
View:
#using (Html.BeginForm("uploadCustomImage", "W", new { id=ViewBag.id }, FormMethod.Post, new { enctype = "multipart/form-data", name="uploadingimage" }))
{
<input name="file" id="file" type="file" />
#Html.SubmitButton()
}
It enters into the controller fine, so routing is all good. But file is always null. I've tried several different things: renaming the input/object, not using a file argument and calling this:
HttpPostedFileBase file = Request.Files["file"];
(which also turns out null)
I tried including a formcollection as a parameter (with and without unnecessary form elements). Still this file is null.
I am of course selecting a file before I press submit =P I've tried multiple files; with very basic filenames (no weird unicode, even no spaces) and also weirder ones. Large files, small files.
Everything comes out null! Where have I gone wrong?
your names don't line up... you need to model bind your file control called "postedFile" in your controller
Try it like this:
#using (Html.BeginForm("uploadCustomImage", "W", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="fileToUpload" type="file" />
<input type="submit" />
}
[HttpPost]
[ValidateInput(false)]
public ActionResult uploadCustomImage(int id, HttpPostedFileBase fileToUpload)
{}
[EDIT]
I've just implemented an upload feature in a project I'm working on and it works.
#using (Html.BeginForm("Import", "MY_CONTROLLER", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" id="UploadedXlsFile" name="UploadedXlsFile"/>
<input type="submit" id="Submit" name="Submit" value="Submit"/>
}
public ActionResult Import()
{
if (Request.Files["UploadedXlsFile"].ContentLength > 0)
{
.............Do stuff ................
}
}
The previous code works for me. If I put a break point inside the Action method, I can see the file isn't null.