Request.files is Empty in MVC file upload - asp.net-mvc

I have the same issue
#using (Html.BeginForm("CreateRequest", "SupportRequest", FormMethod.Post, new { id = "frmStemplate", enctype = "multipart/form-data" }))
{
<td><input type="file" name="FirstFile" id="FirstFile" class="button" />
<input type="button" class="button" id="FirstFileupload" value="upload" onclick="Javascript:DocumentUpload();"/>
}
<script language="javascript" type="text/javascript">
function DocumentUpload()
{
var BrowseFile = $('#FirstFile').val();
if (BrowseFile != null && BrowseFile != "") {
alert(BrowseFile);
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Content("~/SupportRequest/UploadFiles")?fileElementId=' + BrowseFile,
success: function (data) {
alert('Hi'); //debugger;
if (data.Result == "SUCCESS") {
alert('Hi');
}
else {
ShowInfo('Document Uploaded Successfully');
}
}
});
}
}
</script>
On the controller side, I have:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFiles(string fileElementId, FormCollection formColl)
{
var FirstFile = Request.Files;
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].HasFile()) continue;
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
string filename = Path.GetFileName(Request.Files[upload].FileName);
Request.Files[upload].SaveAs(Path.Combine(path, filename));
}
return Json(new { Filename = "" });
}
But my Request.Files is always null.
I tried several things, like changing the code to Request.Files["FirstFile"], etc. Each time, the file collection is empty.

You need to use HttpPostedFileBase in controller action parameters inorder to get the filedata that you have posted.
Please read this full article by Phil Haack

Since you are creating the post of the data you will need to post the file data. see this post:
How can I upload files asynchronously?

I did the different way using form collection that can easily Upload files.Like u did add that line inside begin form in cshtml page.
public ActionResult Create([Bind(Include="Id,Name,Pic,ActiveStatus")] FormCollection form)
{
string Pic = "";
var file = Request.Files[0];
if (file.ContentLength > 0)
{
Pic = string.Format("~/Uploads/Category/{0}", file.FileName);
file.SaveAs(HttpContext.Server.MapPath(Pic));
}
ItemCategory obj = new ItemCategory
{
Name = form["Name"].ToString(),
Pic = file.FileName
};
db.ItemCategories.Add(obj);
db.SaveChanges();
return RedirectToAction("Index");

Related

how to get ID from URL in asp.net MVC controller

I want to get the ID from URL in ASP.NET MVC Controller and insert it into Project_ID, the bellow is my code, i tried but its now working for me.
http://localhost:20487/ProjectComponent/Index/1
My Controller
[HttpPost]
public JsonResult SaveComponent(OrderVM O, int id)
{
bool status = false;
if (ModelState.IsValid)
{
using (Entities db = new Entities())
{
ProjComponent ProjComponent = new ProjComponent { project_id = id, title = O.title, description = O.description };
foreach (var i in O.ProjComponentActivities)
{
ProjComponent.ProjComponentActivity.Add(i);
}
db.ProjComponents.Add(ProjComponent);
db.SaveChanges();
status = true;
}
}
}
You can always use a hidden field and update it by jquery/javscript and send it to back end in ajax helper.....
Make sure 1.name should be exactly name as ActionMethod param and 3.Jquery ,jQuery Validate and jQuery unobstrusive ajax is loaded correctly
My code .cshtml
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<div>
#{
AjaxOptions options = new AjaxOptions();
options.HttpMethod = "POST";
options.OnBegin = "OnBeginRequest";
options.OnSuccess = "OnSuccessRequest";
options.OnComplete = "OnCompleteRequest";
options.OnFailure = "OnFailureRequest";
// options.Confirm = "Do you want to Add Country ?";
options.UpdateTargetId = "divResponse";
options.InsertionMode = InsertionMode.InsertAfter;
}
#using (Ajax.BeginForm("AjaxSend", "Stackoverflow", options))
{
<input type="hidden" name="project_id" id="project_id" value="project_id" />
<input type="submit" value="Click me" />
}
</div>
<div id="divResponse">
</div>
<script>
$(function() {
var url = window.location.href;
var array = url.split('/');
var lastsegment = array[array.length - 1];
console.log(lastsegment);
$('#project_id').val(lastsegment);
});
function OnBeginRequest() {
console.log('On Begin');
}
function OnCompleteRequest() {
console.log('On Completed');
}
function OnSuccessRequest() {
console.log('On Success');
}
function OnFailureRequest() {
console.log('On Failure');
}
</script>
and Controller
[HttpPost]
public JsonResult AjaxSend(String project_id)
{
//rest goes here
return Json(new { Success = true });
}
this link may help link
you can get the id from URL Like This:
Cotroller:
public ActionResult Index(int id)
{
ViewBag.ID = id;
Your Code......
return View(...);
}
View:
#{
ViewBag.Title = "Index";
var ID = ViewBag.ID;
}
Now you have an ID in the variable

Using Ajax.BeginForm helper in MVC 5 for uploading picture issue [duplicate]

I'm trying to upload a file using Ajax.BeginForm(), but it's not working out.
My view contains:
#using (Ajax.BeginForm("UploadFile", null, new AjaxOptions { HttpMethod="POST", UpdateTargetId = "result" }, new { enctype = "multipart/form-data" }))
{
<label id="lblUploadNewFile" for="fileUploadControl">Upload New File</label>
<input type="file" name="fileToUpload" id="fileUploadControl"/>
<input id="btnFileUpload" type="submit" value="Upload" />
<span id="result" />
}
and the corresponding Controller is:
[HttpPost]
public string UploadFile(FormCollection formData)
{
HttpPostedFileBase file=null;
try
{
file = Request.Files[0];
}
catch { }
if ( file!=null && file.ContentLength > 0)
{
file.SaveAs(string.Concat(
AppDomain.CurrentDomain.BaseDirectory,
Path.GetFileName(file.FileName)));
return "Successfully Uploaded";
}
else
{
return "Upload Failed, please try again.";
}
}
The problem is that it's uploading the file, but no longer doing any asynchronous posts when I remove jquery.unobtrusive-ajax.js. Instead, it does a full post-back.
When I add jquery.unobtrusive-ajax.js in my view, it's doing it asynchronously, but it is not sending an upload file in the form data. No file is being sent to the server in Request.Files[].
You cannot upload files using AJAX. This is not supported. If you want to do that you could either use some file upload plugin such as Uploadify or Blueimp File Upload or use the HTML 5 File API if the client browser supports it.
You can do this without additional libraries.
I came across this little hack, which resolves it nicely
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
Found http://www.acnenomor.com/1762557p1/c-mvc3-ajaxbeginform-to-upload-file-not-working
You can do this to get this work:
get jquery.form library from nuget and import it to your cshtml file.You should create your form with #Html.BeginForm.
then bottom of your form write this script to ajax-ify your form:
$(function(){
$('#formId').ajaxForm({
complete:function(xhr){...},
success:function(){...},
error: function(){...}
});
});
With these steps you can pass a file to controller.
very simple solution:
#using (Ajax.BeginForm("action", "controller", new AjaxOptions
{
HttpMethod = "post",
InsertionMode = InsertionMode.Replace,
OnBegin = "startLoader",
OnSuccess = "Update_Record",
UpdateTargetId = "Succ_Msg"
},new { enctype = "multipart/form-data" }))
notice the new { enctype = "multipart/form-data" }
which tells the razor page to add the enctype that can pass HttpPostedFileBase
good luck:).

File is not getting saved

In my MVC application am allowing the user to upload PDF file and uploaded file gets saved in the folder. the file is getting uploaded correctly,but its not getting saved in the folder ...
View code is:
<a class="upload" onclick="upload(this);">
function upload(box) {
var box = dhtmlx.modalbox({
title: "Upload File",
text: "<div id='form_in_box'><div>Choose a PDF file to upload <hr/><label>Enter the URL <input type='file' name='file' id='file' style='width: 400px; height: 27px;'></label><br></div><div><span class='dhtmlx_button'><input type='submit' value='Upload File' style='width: 86px' onclick='save_file(this)'></span><span class='dhtmlx_button'><input type='button' value='Cancel' onclick='close_file(this)' style='width:80px;'></span></label></div></div>",
width: "300px"
});
}
function save_file(box) {
var filename = $("#filename").val();
if (filename == "") {
alert("Enter the URL");
return false;
}
dhtmlx.modalbox.hide(box);
dhtmlx.message("Uploading the file");
$.post("/FileUpload/UploadURL",
{ filename: '' + filename + '' });
}
Controller code is:
public ActionResult UploadURL(FormCollection data)
{
var filename=data["filename"];
SaveNewFile(filename);
return View();
}
public ActionResult SaveNewFile(string file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file) ?? "";
if (file.Length > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_fileUploadPath),
Path.GetFileName(file));
if (!System.IO.File.Exists(filePath))
{
filePath = Server.MapPath(_fileUploadPath + file);
TempData["UploadValidationMessage_Success"] = "File upload Succeeded.";
return View();
}
else
{
TempData["UploadValidationMessage_Failure"] = "File already exist.";
return View();
}
}
else
{
TempData["UploadValidationMessage_Failure"] = "Only PDF files are supported. Try again...";
return View();
}
}
You are not saving it. Just see the below post for how to save file:
File upload in MVC
For a complete tutorial: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx
where in your code are you actually saving the file??? Try making use of
"HttpPostedFileBase" class.
Here's the sample Code
Use HttpPostedFileBase uploadFile parameter to accept Uploading file and SaveAs(filePath); to save!
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
Also change your JQuery Post to Jquery Ajax post
$('form').submit(function(event) {
event.preventDefault();
var file = $("#filename").val();
file = file.serialize();
$.ajax({
type: "POST",
contentType:attr( "enctype", "multipart/form-data" ),
url: "/FileUpload/UploadURL",
data: file,
success: function( data )
{
alert( data );
}
});
return false;
}
</script>
first you need to tell the EncType for the form . Without encType file will not be posted to the server
<form action="" method="post" enctype="multipart/form-data">
</form>
for razor
#using (Html.BeginForm("Index", "yourCOntroller", FormMethod.POST, new { enctype = "multipart/form-data" }))
{
// some stuff
}

Ajax file upload With ASP.NET MVC

Has anybody any help with using this control( http://www.phpletter.com/Demo/AjaxFileUpload-Demo/ ) with ASP.NET MVC
I've tried, but in my controller the HttpPostedFile is always null.
Try
public ActionResult Upload(HttpPostedFileBase file) { ... }
in View <input type="file" name="file" id="file" />
<script type="text/javascript">
$("#formname").bind("submit", function () {
var ext = $('#file').val().split('.').pop().toLowerCase();
if (ext != "") {
if ($.inArray(ext, ['gif', 'png', 'bmp', 'jpg', 'jpeg']) == -1) {
alert('Invalid file extension!');
return false;
}
}
});
</script>
in Controller
public ActionResult Upload(HttpPostedFileBase file)
{
string fileName = "";
if (file != null)
{
if (file.ContentLength > 0)
{
fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
string filePath = Path.Combine(HttpContext.Server.MapPath("~/FileFolder"), fileName);
file.SaveAs(filePath);
}
}
}

File Uploading in Asp.Net MVC

I am trying to make a file uploading page in my MVC project. First of all i want to manage this locally.
My Questions are:
1- Here is my controller and view. Is there any thing that I have to do to make this code work? I mean defining a model or using jquery, etc. What is the process when a file is being uploaded?
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("C:/Users/marti/../PhotoGallery/myimages"),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
}
return View();
}
Here is the View:
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File" />
2- When i debug this, It never goes to controller.
You may need the enctype='multipart/form-data' on your view form:
#model ImageModel
#{
ViewBag.Title = "New Image";
}
<div class="content-form-container width-half">
<form id='PropertiesForm' action='#Url.Action(ImageController.Actions.Add, ImageController.Name)' method='post' enctype='multipart/form-data' class='content-form'>
#Html.Partial("ImageName")
<fieldset class='content-form-1field'>
<div class='legend'>
file to upload
</div>
#Html.LabelledFileInput(ImageView.FileName, string.Empty)
</fieldset>
<div class='buttons'>
#Html.Button("button-submit", "submit")
</div>
</form>
</div>
#section script{
#Html.JavascriptInclude("~/js/image/new.min.js")
}
And here is my controller code:
[HttpPost]
[MemberAccess]
public ActionResult Add()
{
var name = ImageView.ImageName.MapFrom(Request.Form);
if (Request.Files.Count == 0)
{
RegisterFailureMessage("No file has been selected for upload.");
return ValidationFailureAdd(name);
}
var file = Request.Files[0];
if (file == null || file.ContentLength == 0)
{
RegisterFailureMessage("No file has been selected for upload or the file is empty.");
return ValidationFailureAdd(name);
}
var format = ImageService.ImageFormat(file.InputStream);
if (format != ImageFormat.Gif && format != ImageFormat.Jpeg && format != ImageFormat.Png)
{
RegisterFailureMessage("Only gif, jpg and png files are supported.");
return ValidationFailureAdd(name);
}
if (query.HasName(name))
{
RegisterFailureMessage(string.Format("Image with name '{0}' already exists.", name));
return ValidationFailureAdd(name);
}
using (var scope = new TransactionScope())
{
var id = Guid.NewGuid();
var fileExtension = ImageService.FileExtension(format);
Bus.Send(new AddWikiImageCommand
{
Id = id,
Name = name,
FileExtension = fileExtension
});
var path = Path.Combine(ApplicationConfiguration.MediaFolder,
string.Format("{0}.{1}", id.ToString("n"), fileExtension));
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
file.SaveAs(path);
scope.Complete();
}
return RedirectToAction(Actions.Manage);
}
There are some custom bits in there so you can ignore those. The gyst of what you need should be there.
HTH

Resources