Ajax file upload With ASP.NET MVC - 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);
}
}
}

Related

Render HTML file into view - MVC 5

I upload a Html file with Dropzone.js, as into site examples :
//Upload view
#using System.Text;
#{
Layout = null;
string path = ViewBag.path;
}
#if (String.IsNullOrEmpty(fileName))
{
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/dropzone")
<form action="#Url.Action("Upload", "Home")" class="dropzone" id="dropzoneJsForm"></form>
<button id="submit-all">Submit All Files</button>
<script type="text/javascript">
Dropzone.options.dropzoneJsForm = {
//prevents Dropzone from uploading dropped files immediately
autoProcessQueue: false,
init: function () {
var submitButton = document.querySelector("#submit-all");
var myDropzone = this; //closure
submitButton.addEventListener("click", function () {
//tell Dropzone to process all queued files
myDropzone.processQueue();
});
}
};
</script>
}
else
{
#Html.Raw(System.Web.HttpUtility.HtmlEncode(File.ReadAllText(path)))
}
//HomeController
public ActionResult Upload()
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
if (file.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
ViewBag.path = path;
}
}
return View();
}
The file was saved,the view can read it but the page did not display anything.
I can not figure out what's not working. If I active the debugger seems that everything is ok but in the end the page did not draw the html tag of the file. Can you help me or suggest a possible solution
Thank you so much
Instead HttpUtility.HtmlDecode, can you please check HttpUtility.UrlDecode, assuming your file is pure html, not html characters.

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
}

Request.files is Empty in MVC file upload

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");

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

File upload MVC

With the following markup in my view:
<form action="Categories/Upload" enctype="multipart/form-data" method="post">
<input type="file" name="Image">
<input type="submit" value"Save">
</form>
And in my controller:
public ActionResult Upload(FormCollection form)
{
var file = form["Image"];
}
The value of file is null.
If I try it in a different view using a different controller Controller and it works with the same code.
I have VS2008 on Vista, MVC 1.0.
Why?
Malcolm
Use HttpPostedFileBase as a parameter on your action. Also, add the AcceptVerb attribute is set to POST.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Upload(HttpPostedFileBase image)
{
if ( image != null ) {
// do something
}
return View();
}
This code is quite in the spirit/design of ASP.NET MVC.
Not to be picky here or anything, but here's how the code ought to look, as Daniel is missing a few minor details in the code he's supplied...
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadPlotImage(HttpPostedFileBase image)
{
if ( image != null )
{
// do something
}
return View();
}
Try this code:
public ActionResult Upload()
{
foreach (string file in Request.Files)
{
var hpf = this.Request.Files[file];
if (hpf.ContentLength == 0)
{
continue;
}
string savedFileName = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "PutYourUploadDirectoryHere");
savedFileName = Path.Combine(savedFileName, Path.GetFileName(hpf.FileName));
hpf.SaveAs(savedFileName);
}
...
}
Even I was facing a problem , The value was null in image at
public ActionResult UploadPlotImadge(HttpPostedFileBase image)
Earlier I didn't add [AcceptVerbs(HttpVerbs.Post)] which I added. Even after adding it, it didn't work because the second part I was missing, enctype="multipart/form-data", needed to be in the form tag ..
Now it works for me ....
try this class and below action and fix folder path in AppSetting.
config:
<appSettings>
<add key="UploadFolerPath" value="..Your folder path" />
</appSettings>
view:-
<form action="Account/AddImage" id="form_AddImage" method="post" enctype="multipart/form-data">
<input type="file" id="Img" name="Img" class="required" />
<input type="submit" value="Upload" id="btnSubmit" />
</form>
Class:-
public class FileUpload
{
public string SaveFileName
{
get;
set;
}
public bool SaveFile(HttpPostedFileBase file, string FullPath)
{
string FileName = Guid.NewGuid().ToString();
FileName = FileName + System.IO.Path.GetExtension(file.FileName);
SaveFileName = FileName;
file.SaveAs(FullPath + "/" + FileName);
return true;
}
}
//Post Action
[HttpPost]
public ActionResult AddImage(FormCollection Form)
{
FileUpload fileupload = new FileUpload();
var image="";
HttpPostedFileBase file = Request.Files["Img"];
if (file.FileName != null && file.FileName != "")
{
if (upload.ContentLength > 0)
{
fileupload.SaveFile(Request.Files["Img"], Server.MapPath(AppSetting.ReadAppSetting("UploadFolerPath")));
image = fileupload.SaveFileName;
// write here your Add/Save function
return Content(image);
}
}
else
{
//return....;
}
}

Resources