How do I get the value of input file field using MVC5? - c#

I want to let the user select a file from his/her computer, and then upload it to Flickr. The point is that, when I upload a custom image from my computer, it all works fine, but when I add an extra field for the input file but program suddenly doesn't work.
Test.cshtml:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset>
<input type="file" name="file" />
<input type="submit" value="Upload!" />
</fieldset>
}
HomeController.cs:
public ActionResult Upload(HttpPostedFileBase file, FormCollection form)
{
if (Request.QueryString["oauth_verifier"] != null && Session["RequestToken"] != null)
{
// Flickr relevant code...
var tmpFilePath = Server.MapPath("~/App_Data/Uploads/Pictures");
if (file == null || file.ContentLength == 0)
{
return RedirectToAction("Index"); // It keeps hitting this!
}
var filename = Path.GetFileName(file.FileName);
var path = Path.Combine(tmpFilePath, filename);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
file.SaveAs(path);
string photoId = flickr.UploadPicture(path, "Test picture");
if (String.IsNullOrEmpty(photoId))
{
System.Diagnostics.Debug.WriteLine("Upload failed!");
}
System.IO.File.Delete(path);
}
else
{
// Flickr relevant code...
}
return View("Test");
}
As long as I know, because MVC is a server-side framework, first of all I need to upload the picture to my server, and then upload it to Flickr. The point is that, I want to put the file in my App_Data/Upload/Pictures folder, and then upload it to Flickr, and afterwards delete it from there. So, I want to keep my server clean.
UPDATE: It keeps hitting the return RedirectToAction("Index"); part, and redirects.

You're missing enctype="multipart/form-data" from you form tag. Without that, file data is not uploaded to the server when the form is submitted.
Change your form call to:
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

Related

How to upload image with custom name with it's original extension?

I'm trying to upload images in a form which I basically have done already, but I want the image to be named specifically for each user who registers.
For example, each email will be unique, if there is another email already in the database then the form will return false (it will not let him/her register).
So what I did was change the file name to the email he/she typed in the form.
But now the file will not have it's original extension (.jpg .png etc).
Is there a way I could pull the file original extension?
Here's what I have in my controller:
[HttpPost]
public AcitonResult Register(Registration signingUp, HttpPostedFileBase avatar)
{
var db = new AvatarDBEntities();
if (ModelState.IsValid)
{
var FindEmail = db.tblProfiles.FirstOrDefault(e => e.PROF_Email == signingUp.Email);
if (FindEmail == null)
{
var Data = db.tblProfiles.Create();
Data.PROF_Email = signingUp.Email;
if (avatar != null)
{
string profpic = System.IO.Path.GetFileName(avatar.FileName);
string profpic_name = signingUp.Email + ".jpg"; //this is what I'm trying to change
string path = System.IO.Path.Combine(Server.MapPath("~/assets/images/user_images/avatars"), profpic_name);
avatar.SaveAs(path);
}
db.tblProfiles.Add(Data);
db.SaveChanges();
}
else
{
ModelState.AddModelError("Email", "That Email already exist.");
return View();
}
}
return View();
}
View:
#using (Html.BeginForm("Register", "Main", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(r => r.Email, new { #class = "custom-input Email" })<br/>
#Html.ValidationMessageFor(a => a.Email)<br/>
<label for="avatar">Profile picture:<span class="required">*</span></label><br />
<input type="file" name="avatar" id="avatar" /><br/>
<input type="submit" />
}
The image is in the folder with the name as their email and the extension of .jpg.
I just want to pull the extension of the original file and add it after it pulls the email value.
Thanks.
What I think you're looking for is
Path.GetExtension(string fileName)
So your code becomes
string profpic_name = signingUp.Email + Path.GetExtension(avatar.FileName);
There is a method called Path.GetExtension
Store the extension in a temp variable first, then use it later.
string tempExtension = Path.GetExtension(avatar.FileName);

Upload a picture using ASP.NET MVC4 RAZOR

I am using kendo mobile to build a mobile application in which the user will be able to click and upload a photo. When they first enter the page, it will show their current photo, I want to be able to click and open file explorer on their device and have the ability to show a preview of their photo in place of the old one. Then when the click done it will send it to my MVC controller where I can then send it to where I want. I cant figure out how to send my file to the controller.
HTML
<div id="NewAccountUploadContainer">
<img id="NewAccountUpload" src="~/Images/btnCamera.png" data-bind="click: uploadPhoto" />
#using (Html.BeginForm("SendNewPhoto", "MobilePlatform", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input id="ImageUploadBtn" style="display: none" type="file" accept="image/*" />
<input type="submit" value="OK" style="display: none" />
}
<div id="ImgUploadTxt" data-bind="click: uploadPhoto">
Upload a<br />
different photo.
</div>
The #ImageUploadBtn will be triggered by the #NewAccountUpload or #ImgUploadTxt clicks in jquery which works, but I cant get it to display a file or send to my controller when I trigger the submit.
C# Controller
[HttpPost]
public ActionResult SendNewPhoto(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");
}
The file is always null at this point.
I'm using the Kendo for mvc4, and a mobile implementation, and I'm using the follow code, works for me:
View:
#(Html.Kendo().Upload()
.Name("files")
)
Controller
public ActionResult Submit(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
TempData["UploadedFiles"] = GetFileInfo(files);
}
return RedirectToAction("Result");
}
public ActionResult Result()
{
return View();
}
private IEnumerable<string> GetFileInfo(IEnumerable<HttpPostedFileBase> files)
{
return
from a in files
where a != null
select string.Format("{0} ({1} bytes)", Path.GetFileName(a.FileName), a.ContentLength);
}

ASP.NET MVC open a xml and show in textarea

In my view, I want to open a xml file manually with a browse button and then be able to send the content of the xml to a text area with a submit button.
Here is some of my code, but I don't know how to display the xml content in my text area.
View :
#using (Html.BeginForm("OpenFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" id="file"/>
<input type="submit" value="OK"/> }
#Html.TextAreaFor(x => x.XMLContent, 15, 80, null)<p>
Controller :
[HttpPost]
public ActionResult OpenFile(HttpPostedFileBase file)
{
string content = string.Empty;
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract file path
var filePath = Path.GetFullPath(file.FileName);
using (StreamReader reader = new StreamReader(filePath))
{
content = reader.ReadToEnd();
}
}
return View("Index");
}
You need to pass the xml to the view somehow.
One simple option is to use the dynamic ViewBag.
So before returning the view you could add this:
ViewBag.content = content;
And then, in the view:
#Html.TextArea("TextAreaName", (string)ViewBag.content)

ASP.net MVC upload image NullReferenceException

I've implemented simple create method to put data in database, and it worked fine. I've decided to add image upload, but I keep getting NullReferenceException (file is null) and I can't figure out why.
I hope you can help me!
Here's my code:
[Authorize]
public ActionResult Create()
{
ViewBag.CategoryId = new SelectList(_categoryRepository.GetAllCategories().AsEnumerable(), "CategoryId",
"Name");
return View();
}
//
// POST: /Advert/Create
[HttpPost, Authorize]
public ActionResult Create(CompetitionDTO competitionDTO, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
string fileExtension = Path.GetExtension(fileName);
if ((fileExtension == ".jpg") || (fileExtension == ".png"))
{
string path = Path.Combine(Server.MapPath("~/Uploads/Images"), fileName);
file.SaveAs(path);
competitionDTO.ImageURL = path;
}
}
if (ModelState.IsValid)
{
_competitionRepository.AddCompetition(competitionDTO, WebSecurity.CurrentUserId);
return RedirectToAction("Index");
}
ViewBag.CompetitionId = new SelectList(_competitionRepository.GetAllCompetitions().AsEnumerable(),
"CompetitionId", "Name");
return View(competitionDTO);
}
}
and View
<div>
#using (Html.BeginForm("Create", "Competition", FormMethod.Post, new
{
enctype = "multipart/form-data"
, id = "parentForm"
}))
{
<input type="file" name="file" id="file"/>
<input type="submit" value="Create" />
}
</div>
EDIT
I if I wasn't clear enough:
I know how to insert data to database and I know how to upload file, and I want when I click submit that those 2 things happen at same time
It was my mistake I had two Html.BeginForms, now I merged them into one and it works fine

C# MVC problem with file upload

I'm trying to make uploading a file to the server at my mvc project. I wrote my class,
public class MyModule: IHttpModule
which defines the event
void app_BeginRequest (object sender, EventArgs e)
In it, I check the length of the file that the user has selected to send.
if (context.Request.ContentLength> 4096000)
{
//What should I write here, that file is not loaded? I tried
context.Response.Redirect ("address here");
//but the file is still loaded and then going on Redirect.
}
In ASP.NET MVC you don't usually write http modules to handle file uploads. You write controllers and inside those controllers you write actions. Phil Haack blogged about uploading files ni ASP.NET MVC:
You have a view containing a form:
<% using (Html.BeginForm("upload", "home", FormMethod.Post,
new { enctype = "multipart/form-data" })) { %>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
<% } %>
And a controller action to handle the upload:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
if (file.ContentLength > 4096000)
{
return RedirectToAction("FileTooBig");
}
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}

Categories

Resources