AntiForgeryToken not being received when using plupload in form submission - asp.net-mvc-3

I'm using Plupload to allow multiple images to be uploaded to an mvc3 web app.
the files upload OK, but when i introduce the AntiForgeryToken it doesn't work, and the error is that no token was supplied, or it was invalid.
I also cannot get the Id parameter to be accepted as an action parameter either, it always sends null. So have to extract it myself from the Request.UrlReferrer property manually.
I figure plupload is submitting each file within the upload manually and forging its own form post.
My form....
#using (#Html.BeginForm("Upload", "Photo", new { Model.Id }, FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)
<div id="uploader">
<p>You browser doesn't have HTML5, Flash or basic file upload support, so you wont be able to upload any photos - sorry.</p>
</div>
<p id="status"></p>
}
and the code that wires it up...
$(document).ready(function ()
{
$("#uploader").plupload({
// General settings
runtimes: 'html5,flash,html4',
url: '/Photo/Upload/',
max_file_size: '8mb',
// chunk_size: '1mb',
unique_names: true,
// Resize images on clientside if we can
resize: { width: 400, quality: 100 },
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,gif,png" }
],
// Flash settings
flash_swf_url: 'Content/plugins/plupload/js/plupload.flash.swf'
});
$("#uploader").bind('Error', function(up, err)
{
$('#status').append("<b>Error: " + err.code + ", Message: " + err.message + (err.file ? ", File: " + err.file.name : "") + "</b>");
});
// Client side form validation
$('uploadForm').submit(function (e)
{
var uploader = $('#uploader').pluploadQueue();
// Validate number of uploaded files
if (uploader.total.uploaded == 0)
{
// Files in queue upload them first
if (uploader.files.length > 0)
{
// When all files are uploaded submit form
uploader.bind('UploadProgress', function ()
{
if (uploader.total.uploaded == uploader.files.length)
$('form').submit();
});
uploader.start();
} else
alert('You must at least upload one file.');
e.preventDefault();
}
});
});
and here is the controller action that receives it...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(int? id, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var parts = Request.UrlReferrer.AbsolutePath.Split('/');
var theId = parts[parts.Length - 1];
var fileName = theId + "_" + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return Content("Success", "text/plain");
}
As you can see, i have had to make the id parameter nullable, and i extract this manually in the action method.
How can i ensure that the values are sent with each form post correctly?

short answer : YES!
use multipart_params options like this:
multipart_params:
{
__RequestVerificationToken: $("#modal-dialog input[name=__RequestVerificationToken]").val()
}

short answer: you can't.
What you can do in this case is pass your token either as another multipart paramenter (if using that), or as part of the URL as a GET parameter, but nothing from the form will be sent by plupload as it builds its own request.
Another possibility is using custom headers to pass back the token to the server (plupload has a headers option), but whichever is the method you use, you will have to process it on your backend to validate it.

Related

How I can upload a file using html input type "file" through ajax with web API model binder

I'm using a MVC 5 web Api Controller, and I want my data coming through ajax with file to automatically bind?
You can append your uploaded file to FormData and send it via Fetch API.
Here's a demo to get started:
window.onload = () => {
document.querySelector('#myFile').addEventListener('change', (event) => {
// Just upload a single file, if you want multiple files then remove the [0]
if (!event.target.files[0]) {
alert('Please upload a file');
return;
}
const formData = new FormData();
formData.append('myFile', event.target.files[0]);
// Your REST API URL here
const url = "";
fetch(url, {
method: 'post',
body: formData
})
.then(resp => resp.json())
.then(data => alert('File uploaded successfully!'))
.catch(err => {
alert('Error while uploading file!');
});
});
};
<input id="myFile" type="file" />
After that just get the file from the current request in your API action method.
[HttpPost]
public IHttpActionResult UploadFile()
{
if (HttpContext.Current.Request.Files.Count > 0)
{
var file = HttpContext.Current.Request.Files[0];
if (file != null)
{
// Do something with file now
}
}
return Ok(new { message = "File uploaded successfully!" });
}

Navigate to another Page after appointment has been saved in kendo scheduler

I have got this scheduler displayed but not binding to tasks. The scheduler in the view. I am using java script method to read/create call to web api
#(Html.Kendo().Scheduler<TaskViewModel> ()
.Name("AppointmentSearchScheduler")
.DataSource(dataSource => dataSource
.Custom()
.Schema(schema => schema
.Model(m => {
m.Id(f => f.TaskID);
m.Field(f => f.OwnerID).DefaultValue(1);
}))
.Transport(new {
read = new Kendo.Mvc.ClientHandlerDescriptor() {
HandlerName = "customRead"
},
create = new Kendo.Mvc.ClientHandlerDescriptor() {
HandlerName = "customCreate"
}
})))
Below is javascript handler method I am not including create handler for brevity.
function customRead(options){
//get the selected Row of the kendo grid
var selectedRow = $("#locationgridKendo").find("tbody tr.k-state-selected");
var scheduler = $("#AppointmentSearchScheduler").data("kendoScheduler")
//get SelectedRow data
var rowData = $('#locationgridKendo').data("kendoGrid").dataItem(selectedRow);
if (rowData !== null) {
//Convert data to JSON
var rowDataJson = rowData.toJSON();
//extract the location ID
var locationId = rowDataJson.LocationID;
var CalenderweekStartDate = new Date().toISOString();
baseUrl = $('base').attr('href');
$.ajax({
url: baseUrl + 'Schedular/api/GetAppPerLocation?locationId=' + locationId + '&date=' + CalenderweekStartDate,
type: 'GET',
cache: false,
contentType: 'application/json',
success: function (result) {
//This method is hitting and i can see the data being returned
console.log('data is received : ' + result.Data);
options.success(result.Data);
},
error: function (xhr, status, error) {
//alert("Error: Search - Index.js - submitAppointment()");
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
}
Here is the web API controller called by making ajax call . The controller works perfectly when i used the basic read/create syntax . The ajax call complete and it does hit back the success method and returns the data but scheduler for some reason is not binded to incoming data. Here is my controller code
[HttpGet]
[Route("api/GetAppPerLocation")]
public DataSourceResult GetAppointmentPerLocation([ModelBinder(typeof(Usps.Scheduling.Web.ModelBinders.DataSourceRequestModelBinder))] DataSourceRequest request, int locationId, DateTime date) {
List < TaskViewModel > locationAvailableAppointmentList = new List < TaskViewModel > ();
locationAvailableAppointmentList = data.Select(appt => new TaskViewModel() {
TaskID = appt.ServiceAppointmentId,
Title = "Appointment Available",
Start = DateTime.SpecifyKind(appt.AppointmentBegin, DateTimeKind.Local),
End = DateTime.SpecifyKind(appt.AppointmentEnd, DateTimeKind.Local),
Description = "",
IsAllDay = false
}).ToList();
return locationAvailableAppointmentList.ToDataSourceResult(request);
}
For some reason the scheduler is not binding to incoming data . the incoming data works perfectly when i use a basic binding approach but not using transport . My goal for using this approach is once i am done with read(scheduler is not binding now) , on create I need to grab the ID of the newly created task returned by my controller and then pass that id to another mvc controller to render a confirmation page. Any other approach to accomplish this goal will be highly recommended.
Please excuse me for any mistake since this is my first question on stackoverflow.
My goal for using this approach is once i am done with read(scheduler is not binding now) , on create I need to grab the ID of the newly created task returned by my controller and then pass that id to another mvc controller to navigate render a confirmation page.
I speculated that read was not returning correct result so i had to fix that .Also my basic goal was redirection to another page after with appointment id and displaying a confirmation screen. This is how accomplished it . I understand this is not the best approach but it has been more than a year no body answered by question. Here is the approach i took .
I added a error to the model state like this in my controller
if (!String.IsNullOrEmpty(task.TaskID.ToString()))//redirect to confirmation page if the appointment was added to the queue
ModelState.AddModelError("AppointmentID", confirmationNumber);
then on client side i configure the error event on grid like this
.Events(
events => events.Error("RedirectToConfirmationPage"))
Here is the Javascript method details
function RedirectToConfirmationPage(e) {
console.log('RedirecToConfirmationPage method......');
console.log(e);
if (e.errors) {
var appointmentID = "";
// Create a message containing all errors.
$.each(e.errors, function (key, value) {
console.log(key);
if ('errors' in value) {
$.each(value.errors, function () {
appointmentID += this + "\n";
});
}
});
console.log('Newly Generated AppointmentID = ' + appointmentID);
// Redirect URL needs to change if we're running on AWS instead of on local developer machines
if (window.location.href.indexOf('/TestProject.Scheduling') > 1) {
window.location.href = '/Scheduler/AppointmentConfirmation?confirmationNumber=' + appointmentID
}
else {
window.location.href = '/Scheduler/AppointmentConfirmation?confirmationNumber=' + appointmentID
}
}
}
Hope it is helpfull to someone down the road.

Can't get meteor FileCollection package to work

I am (unfortunately) working on a Windows machine so I had to manually add the FileCollection package to my app, but when I run my app, I can access the file collection and file collection methods from the browser console. However, I can't seem to get the event listeners set up on an actual page. (FYI, I am using iron-router for my templating architecture.)
It seems like the code that needs to be called is just not coming in the right order, but I've experimented with where I place the code and nothing seems to make a difference.
The server side code:
// Create a file collection, and enable file upload and download using HTTP
Images = new fileCollection('images',
{ resumable: true, // Enable built-in resumable.js upload support
http: [
{ method: 'get',
path: '/:_id', // this will be at route "/gridfs/images/:_id"
lookup: function (params, query) { // uses express style url params
return { _id: params._id }; // a mongo query mapping url to myFiles
}
}
]
}
);
if (Meteor.isServer) {
// Only publish files owned by this userId, and ignore
// file chunks being used by Resumable.js for current uploads
Meteor.publish('myImages',
function () {
return Images.find({ 'metadata._Resumable': { $exists: false },
'metadata.owner': this.userId });
}
);
// Allow rules for security. Should look familiar!
// Without these, no file writes would be allowed
Images.allow({
remove: function (userId, file) {
// Only owners can delete
if (userId !== file.metadata.owner) {
return false;
} else {
return true;
}
},
// Client file document updates are all denied, implement Methods for that
// This rule secures the HTTP REST interfaces' PUT/POST
update: function (userId, file, fields) {
// Only owners can upload file data
if (userId !== file.metadata.owner) {
return false;
} else {
return true;
}
},
insert: function (userId, file) {
// Assign the proper owner when a file is created
file.metadata = file.metadata || {};
file.metadata.owner = userId;
return true;
}
});
}
The client side code (currently in main.js at the top level of the client dir):
if (Meteor.isClient) {
// This assigns a file upload drop zone to some DOM node
Images.resumable.assignDrop($(".fileDrop"));
// This assigns a browse action to a DOM node
Images.resumable.assignBrowse($(".fileBrowse"));
// When a file is added via drag and drop
Images.resumable.on('fileAdded', function(file) {
// Create a new file in the file collection to upload
Images.insert({
_id : file.uniqueIdentifier, // This is the ID resumable will use
filename : file.fileName,
contentType : file.file.type
}, function(err, _id) {// Callback to .insert
if (err) {throwError('Image upload failed');}
// Once the file exists on the server, start uploading
Images.resumable.upload();
});
});
Images.resumable.on('fileSuccess', function(file) {
var userId = Meteor.userId();
var url = '/gridfs/images/' + file._id;
Meteor.users.update(userId, {
$set : {
"profile.$.imageURL" : url
}
});
Session.set('uploading', false);
});
Images.resumable.on('fileProgress', function(file) {
Session.set('uploading', true);
});
}
I think the issue might be with using IronRouter. I'll assume you are using some layout.html via Iron router and inside it you've added your template for your file table to be shown. (I'm guessing your are following the sampleApp that came with fileCollection.). I had a problem when I did this and it had to do with where I had the code that attached the listeners. The problem is where you have the code "Images.resumable.assignDrop($(".fileDrop"));" in your client file. The way you have it now, that line of code is running before your template is rendered within the layout.html. So the code can not find the DOM element ".fileDrop". To fix this create a layout.js file and use the rendered method like this...
Template.layout.rendered = function(){
Images.resumable.assignDrop($(".fileDrop"));
}

Displaying uploaded files from server in dropzone js

I am using the dropzone js plugin to upload files to a php server. It is working great. I am facilitating the user to update the uploaded files. So once the user clicks on update button, the dropzone appears, and I am able to display the uploaded files in it through a JQuery-AJAX call. But my problem is that though the files are displayed in the thumbnail format, the number of files in the dropzone counts to zero. I feel that the accept function is not being triggered.But if a new file is added to the displaying list the file count is 1 though there are files already existing in it.
I am using the following code to display the files in dropzone:
var mockFile = { name: "Filename", size: 12345 };
myDropzone.options.addedfile.call(myDropzone, mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, "/image/url");
Can anyone help me solve this?
I think you need to push the mockFile in the dropZone manually like this
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("complete", mockFile);
myDropzone.files.push(mockFile);
It's work for me... if you need more code just ask!
Mock file is not uploaded as explained here https://github.com/enyo/dropzone/issues/418
If you want to submit the form use myDropzone.uploadFiles([]); in init()
$('input[type="submit"]').on("click", function (e) {
e.preventDefault();
e.stopPropagation();
var form = $(this).closest('#dropzone-form');
if (form.valid() == true) { //trigger ASP.NET MVC validation
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
myDropzone.uploadFiles([]);
}
}
});
example for U!
jQuery(function($) {
//文件上传
$(".dropzone").dropzone({
url : "pic_upload.jsp?id=<%=request.getParameter("id")%>",
addRemoveLinks : true,
dictRemoveLinks : "x",
dictCancelUpload : "x",
maxFiles : 5,
maxFilesize : 5,
acceptedFiles: "image/*",
init : function() {
//上传成功处理函数
this.on("success", function(file) {
alert("修改前:"+file.name);
});
this.on("removedfile", function(file) {
alert("File " + file.name + "removed");
//ajax删除数据库的文件信息
$.ajax({
type:'post',
url:'pic_delete.jsp?id='+file.name ,
cache:false,
success:function(data){
}
});
});
<%
if(null!=list){
for(PlaceImg img:list){%>
//add already store files on server
var mockFile = { name: "<%=img.getId()%>", size: <%=img.getFilesize()%> };
// Call the default addedfile event handler
this.emit("addedfile", mockFile);
// And optionally show the thumbnail of the file:
this.emit("thumbnail", mockFile, "<%=img.getImgUrl()%>");
<%}
}%>
}
});

Looking for a good example on File upload with asp.net mvc3 & knockout.js

I am trying to look for a good comprehensive example of multiple file upload with asp.net mvc3 & knockout.js. I been looking around but nothing that shows the solution from start to finish! There examples that show what the knockout binding needs to be, but doesn't show how to read the files in the "Controller". Goal is upload and save files to db. Example of saving to a AWS S3 storage is a plus. Please help.
ko binding:
<input type="file" data-bind="value: fileToUpload, fileUpload: fileToUpload, url : 'Client/Upload' " />
ko.bindingHandlers.fileUpload = {
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor())
if (element.files.length && value) {
var file = element.files[0];
var url = allBindingsAccessor().url
xhr = new XMLHttpRequest();
xhr.open("post", url, true);
xhr.setRequestHeader("Content-Type", "image/jpeg");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);
console.log("sending")
// Send the file (doh)
xhr.send(file);
}
}
}
[HttpPost]
public ActionResult Upload()
{
//Not sure what to do here.
}
Also need to do multiple file upload? Not sure how to set the viewmodels.
On the javascript side I would suggest using fineuploader http://fineuploader.com/. you can create a custom binding for updating the viewmodel with the response.
<div data-bind="fileupload: viewModel.fileName"></div>
ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
var $element = $(element);
var fileNameVal = valueAccessor;
var uploader = new qq.FineUploader({
element: $element[0],
request: {
endpoint: 'server/your_upload_service'
},
multiple: true,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'txt']
},
callbacks: {
onComplete: function(id, fileName, responseJSON) {
if (responseJSON.success) {
// update your value
valueAccessor(fileName)
//may need to change this if you pass a reference back
// in your responseJSON such as an s3 key
}
}
}
});
}
};
as for the server side I am not familiar with ASP.net but you should be able to interact with the request data on your endpoint and extract the multipart encoded form parts that contain the image data.
might want to look at these answers
MVC 3 file upload and model binding
File Upload ASP.NET MVC 3.0
also note that fineuploader sends the file in the request with the key "qqfile"

Resources