I am trying to use dropzone.js to upload images in my ASP.NET MVC app. I am able to set-up the dropzone programatically, click on it, select the image and when I click "Open" in the file dialog, the correct Action is hit in the controller. However, the HttpPostedFileBase always comes back as null so I can't do anything with the image. ON the client-side, however, it shows the image thumbnail correctly, eventhough I can't get it on the server side.
This is the HTML:
<div style="float:left;margin-right:2px;" id="mainImage">
<img src="/images/AddImage_button.png" class="dz-message" />
</div>
This is the js code I call after the doc is ready:
var myDropzone = new Dropzone("div#mainImage", { url: "/Market/UploadImage" });
And this is the action call inside of the controller:
public ContentResult UploadImage(HttpPostedFileBase imageFile)
{
if (imageFile == null || imageFile.ContentLength == 0)
{
//.....
}
}
The action is hit but imageFile is null. Does anyone has any ideas? By the way, the "dz-message" class was added in the image placeholder inside the dropzone because before that it was not clickable. I read it somewhere that was a fix for that issue and it worked.
Any ideas why I am getting null for imageFile?
Default parameter name that Dropzone uses is file, and yours is imageFile. Change imageFile to file and it will work
There is a small tweak you may miss.
Happened to me lots of times,
The form element you use, must have it's enctype attribute set like this:
<form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data"/>
Related
I want to be able to receive open/save dialog for a pdf file being returned from controller without using 'Html.Beginform' in ASP.NET MVC. I´m using 'Ajax.Beginform' since I can register events to fire OnBegin and OnComplete (which I think I can´t do when using Html.Beginform, or is it?).
I want to state that the problem is not creating and receiving the file from the server when using 'Html.Beginform' because that works fine, but without the events I want to use. I´m using 'Ajax.Beginform' and the file is being returned from the controller but nothing happens after that client side.
My cshtml
#using (Ajax.BeginForm("CreatePdf", "Print", null, new AjaxOptions() { LoadingElementId = "printLoading", OnSuccess = "printPageComplete"}, new { id = "exportForm" }))
{
//Stuff abbreviated
<input type="button" onclick="onPrint()" />
}
My jQuery
function onPrint()
{
//Stuff abbreviated
$("#exportForm").submit();
}
function printPageComplete(result)
{
//this 'result' variable is obviously holding the file from the controller
//stuff abbreviated
//TODO: I need to open file dialog here
}
My Controller
[HttpPost]
public ActionResult CreatePdf(FormCollection collection)
{
//Stuff abbreviated
return File(thePdf, _mimeTypes[ExportFormat.Pdf], "thePdf.pdf")
}
As you can see I´ve managed to get this far as in the printPageComplete function but I´m not sure where to go from here. Should I continue using the ajax form or should I stick with the html form and try to find other way to fire the events I so sorely need to use?
Perhaps I´m going about this all wrong and your help would be very well appreciated.
You can post a form without using Ajax.BeginForm. It is more work, but gives you more flexibility:
$('#exportForm').submit(function (e){
e.preventDefault();
//Do any validation or anything custom
$.ajax({
//set ajax settings
success: function(){
// Handle the success event
}
});
});
So I am trying to implement Uploadifive 1.0 with Asp.NET MVC. Using the debugger mode, I know that the upload action is successfully passed to the Controller and the Server variables are passed as well. However, the HttpPostedFileBase variable fileData is always null. I've looked everywhere on google and couldn't find an answer. I found out that the variable has to be called fileData. That doesn't help though.
Here's part of the view:
<form action="<%: Url.Action("SaveFiles", "File") %>" enctype="multipart/form-data">
<input type="file" name="file_upload" id="file_upload" />
</form>
<script type="text/javascript">
(function ($) {
$(document).ready(function () {
$('#file_upload').uploadifive({
'method': 'post',
'uploadScript': 'SaveFiles',
'formData': {'path' : 'documents'}
});
});
})(jQuery);
</script>
Here's the controller action:
[HttpPost]
public ActionResult SaveFiles(HttpPostedFileBase fileData)
{
string uploadFolder = Request.ServerVariables.Get("HTTP_X_PATH");
if(string.IsNullOrWhiteSpace(uploadFolder))
return Json(JsonMessageManager.GetFailureMessage("No upload folder was selected"));
if (fileData != null && fileData.ContentLength > 0)
{
var fileName = Path.GetFileName(fileData.FileName);
var path = Path.Combine(Server.MapPath("~/Content/" + uploadFolder), fileName);
fileData.SaveAs(path);
return Json(true);
}
return Json(false);
}
Any pointers or help would be greatly appreciated. I feel lost.
I had the exact same problem with Uploadifive so I posted on the Uploadify forums on an existing thread (probably yours). The author has since posted an update to the Uploadifive plugin which I downloaded and now this works fine for me. In fact, it works exactly like Uploadify used to including additional form data being available in "Request.Forms" and it no longer prepends the "X_" to the additional form data. I would recommend you try the new version and see how you go.
See the discussion here: http://www.uploadify.com/forum/#/discussion/8223/no-files-attached-to-request
The key is not naming your variable 'fileData,' but rather making sure that your controller and UploadiFive both think it has the same name. For example:
Javascript:
$(document).ready(function () {
$('#fileUploadDiv').uploadifive({
'uploadScript': '/File/Upload',
'fileObjName' : 'file'
});
});
C# Controller:
[HttpPost]
public PartialViewResult Upload(HttpPostedFileBase file)
{
var name = file.FileName;
var stream = file.InputStream;
// etc...
}
As long as fileObjName has the same name as the parameter in your C# controller, you should be fine. I tested it with various names, and the parameter came in null if the names didn't match, and it worked like a charm when they did match.
If the parameter still doesn't work, you should be able to access the data using this.Request.Files inside of your controller. It looks like that data comes through regardless of parameter names.
I'm trying to find a decent way of allowing users to upload a profile photo on an edit profile page.
I've tried out Uploadify but this doesn't appear to work under some of the more recent Google Chrome browser releases.
Ideally, I just want to offer the user the ability to replace a placeholder profile image with an image of their own, via a simple upload button (preferably ajax), and once an image has been upload, to show a 'delete' button to remove the uploaded photo and re-instate the default placeholder image.
Are there any other alternatives that play nicely across all the main browsers and integrate easily into an MVC application?
To upload with jQuery only with HTML 5, and not all browser are able to this.
You can do something like this.
You need to have a IFRAME that 'll be use to make the post with the file.
Like this:
<iframe id="targetUpload" name="targetUpload"></iframe>
In the form you set the target to the iframe.
<form target="targetUpload" name="file" runat="server" method="post" id="file" enctype="multipart/form-data" action="#Url.Content("~/Controller/Upload")">
And a submit button
<input type="Submit" value="Upload">
This is a way to upload files without refresh the page.
You can treat the files before upload with jquery. (File type, size, etc...)
And in yout controller you recive the files:
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//Save the file in the server path
string savePath = Server.MapPath("~/Upload/");
string fileName = file.FileName;
savePath += fileName;
file.SaveAs(savePath);
}
return RedirectToAction("Index");
}
I've a bit of an odd issue with FCKEditor in my MVC project.
I've essentially got a View which renders a Partial View containing my FCKEditor (javascript, html and any other bits to make my control reusable throught my app)
I'm calling FCKEditor by doing the following:
<script src="<%= Url.Content("~/Scripts/fckeditor/fckeditor.js") %>" type="text/javascript" ></script>
<script type="text/javascript">
window.onload = function () {
var sBasePath = '<%= Url.Content("~/Scripts/fckeditor/") %>';
var oFCKeditor = new FCKeditor('FckEditor1');
oFCKeditor.BasePath = sBasePath;
oFCKeditor.ReplaceTextarea();
}
</script>
To validate my form, I'm using jQuery.Validate with the following code:
//FORM VALIDATION
$("#NewPageForm").validate({
errorContainer: "#errorblock-div1, #errorblock-div2",
errorLabelContainer: "#errorblock-div2 ul",
wrapper: "li",
rules: {
titleTxt: "required",
FckEditor1: "required"
},
messages: {
titleTxt: "You must enter a page title.",
FckEditor1: "You must enter at least some content."
},
submitHandler: function (form) {
form.submit();
}
});
Locally, when debugging my project, this works absolutely fine and throws up an error to the user when they leave the editor blank.
However, when I publish the application and run it from the server, whenever the editor has content in, the form won't validate, telling me that my FCKEditor control is empty, when it clearly isn't.
If I take away the validation, and submit the form with all the relevant boxes filled, the collection of collection("FckEditor1") is also empty, but again, running this locally works first time, every time.
I've had a search around and what seems to be happening is that my text area <%= Html.TextArea("FckEditor1", New With {.name = "FckEditor1", .class = "required"})%> isn't being populated with the content entered into the FCKEditor, even though this is the box that FCK is linked to.
The issue exists in all the browsers I've tried (IE8 and FF).
Not sure if it's also worth noting that FCK still renders fine too?
I'm not entirely convinced it's an issue with my code as it runs perfect locally. Is there anything I need to configure server-side or in web.config that could be causing it?
Has anyone else come across this or have any ideas as to how to solve the issue?
EDIT
I think I could be partway there with a fix.
I've added the following so far:
$('#publishBtn').button().click(function () {
if (typeof (FCKeditorAPI) == "object") {
FCKeditorAPI.GetInstance("FckEditor1").UpdateLinkedField();
} else {
alert('this is not an object!');
}
if ($("#FckEditor1").val() == "") {
alert("FCKEditor is empty");
} else {
$("#NewPageForm").submit();
}
});
Though, I now get sent to a blank page when the form is submitted, though nothing in my controller seems to be the issue - at least I don't think so as if there was an issue there, it'd do the same on my local machine.
One thing that may be causing your issue if you are validating on the server is that once it's on IIS you cannot post HTML content without the request validation preventing the FCKContent from being passed. Cassini wont check this so it works on your local machine.
try adding this to your the action which is called when you post to validate:
[ValidateInput(false)]
public ActionResult UpdateAction()
{
}
If possible, use CKEditor instead; it integrates with MVC much better.
http://ckeditor.com/
http://ckeditor.com/what-is-ckeditor
I found the source of my problem, and it's to do with the way I'm handling multiple submit buttons in my controller.
I've tweaked it and it's now fixed.
I have
public class FileController : AsyncController
{
public ActionResult Download(FormCollection form)
{
FileContentResult file = new FileContentResult(Encoding.UTF8.GetBytes("10k file size"),"application/vnd.xls");
file.FileDownloadName = "test.xls";
return file;
}
}
and ofcourse, ajax form
<% var form = Ajax.BeginForm(...) %>
<input type="image" src="...gif" /> // this is my 1st attempt
<%= Ajax.ActionLink(...) %> // 2nd attempt
<% form.EndForm(); %>
i try first method(input type=image). it reach correct Action. but no file download in client side.
Then i try to use Ajax.ActionLink which i really hate. i want nice image button, not link text. Again, it reach correct Action and no file download. But if i open link in another window, there's file download !!
Q. How to make a nice file downlaod with AsyncController
Q. How to make Ajax.ActionLink lok nice
You cannot use Ajax to download files from the server. The reason for this is that even if you succeed to make the async request to the server in the success callback you will get the file contents as sent from the server and you cannot do much with this file on the client side. Remember that javascript cannot access the file system so you won't be able to save it. The way to achieve this is to have a normal HTML <form> which will point to the Download action. When this form is submitted the user will be asked to choose where he wants to save the file and the download will proceed. Also you don't need an AsyncController for this.
Here's an example:
public class FileController : Controller
{
[HttpPost]
public ActionResult Download()
{
return File(
Encoding.UTF8.GetBytes("10k file size"),
"application/vnd.xls",
"test.xls"
);
}
}
and inside your view:
<% using (Html.BeginForm("download", "file", FormMethod.Post)) { %>
<input
type="image"
src="<%: Url.Content("~/content/images/download.png") %>"
value="download"
alt="download"
/>
<% } %>
And in order to make the download button look nice, you could create a nice download.png image which will be used as form submit button.
I use this:
to disable
$('form').removeAttr("data-ajax");
to enable
$('form').attr("data-ajax", "true");
for a form with 3 submit 1 to refresh 2 to download file
All post to the same ActionResult but 2 of them have param to download as csv or as pdf
when download just disable ajax submission.
i found a way!!
just create iframe that has regular form and use jquery to trigger to.
$("iframe").contents().find("form").submit();
:D
ps credit to Firebug + Google Doc.