FineUploader uploading multiple files as one request - fine-uploader

I need to upload multiple files as one request.
For example, i have two required files (.csv & .ctl) that I need to save.
Basically on the server side, I'm reading the .csv file and checking it against the .ctl file. If certain criteria doesn't match, I don't need to upload it. I'm not sure how or need to update the 'upload' method to read the filenames[]. Nor if I need to update this line "uploader.fineUploader('uploadStoredFiles');" to now accept the filenames[] after the user clicks "Upload now."
<script type="text/javascript">
$(document).ready(function () {
var filenames = [];
var uploader = $("#fine-uploader").fineUploader({
request: {
endpoint: '<%= ResolveUrl("~/Handler/UploadHandler.ashx")%>'
},
autoUpload: false,
text: {
uploadButton: '<span class="glyphicon glyphicon-plus"></span> Select Files'
},
validation: {
allowedExtensions: ['csv', 'ctl']
},
showMessage: function (message) {
// Using Bootstrap's classes
$('#fine-uploader').append('<div class="alert alert-danger">' + message + '</div>');
}
}).on('validate', function (event, fileData) {
return $.inArray(fileData.name, filenames) < 0;
}).on('submitted', function (event, fileId, fileName) {
filenames.push(fileName);
}).on('upload', function (event, fileId, fileName) {
var fileItemContainer = $(this).fineUploader('getItemByFileId', fileId);
$(this).fineUploader('setParams', { uploadType: 'VendorFileType', vendorId: '<%=vendorDropdownList1.CurrentVendorID %>' }, fileId);
}).on('complete', function (event, fileName, fileName, responseJSON) {
if (responseJSON.success) {
var div = document.getElementById('fine-uploader-status');
div.innerHTML = 'Upload process complete.';
}
else {
var div = document.getElementById('fine-uploader-status');
div.innerHTML = 'Upload denied.';
}
});
$('#uploadSelectedFiles').click(function () {
uploader.fineUploader('uploadStoredFiles');
});
});
</script>
//here's the aspx side.
<div id="fine-uploader">
</div>
<div id="fine-uploader-status">
</div>
<button id="uploadSelectedFiles" class="btn btn-primary">
<span class="glyphicon glyphicon-upload"></span>Upload now</button>

Fine Uploader does not support sending multiple files in a single request. This complicates the code unnecessarily and would break some existing features. Each file is sent in a separate request. You say you are performing some server-side checks to prevent uploads, but the files have already been uploaded by the time your server is able to perform these comparisons anyway. It's not clear from your question why you need to upload multiple files in a single request, or what benefit this gives you. If you clarify, perhaps I can provide alternate suggestions.

Related

Dropzone and another input type file?

<input type="file" name="default_image" id="imgInp" value="{{$property->default_image}}">
<div class="dropzone_upload">
<div class="dz-message" data-dz-message>
<span>
<img src='/assets/home/img/cloud_upload.png'/><br/>DRAG AND DROP IMAGES HERE <br/> <span class='or'>or</span> <br/> <a href='javascript:void(0)' class='upload_images'>UPLOAD IMAGES</a>
</span>
</div>
</div>
Now i have a problem when i upload default image and images in dropzone it mix those two so everything puts in default_image[].
Any suggestion how can i fix that?
When i do like this it say that image must be a type of jpeg,bmp,png:
$this->validate($request,[
'default_image' => 'mimes:jpeg,bmp,png|max:2000'
]);
This is my config for dropzone:
Dropzone.options.myDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
addRemoveLinks: true,
previewsContainer: '.dropzone-previews',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 10,
maxFiles: 10,
autoDiscover:false,
paramName:'gallery_images',
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
if (myDropzone.getQueuedFiles().length > 0) {
e.preventDefault();
e.stopPropagation();
myDropzone.processQueue();
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
console.log('sendingmultiple');
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("successmultiple", function(files, response) {
console.log('successmultiple error',response);
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
$("html, body").animate({ scrollTop: 0 }, "slow");
$("#resultMsg").css('display', 'block').text(response.successMsg);
});
this.on("errormultiple", function(files, response) {
console.log('response error',response);
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
};
You need to use the rule like this:
$this->validate($request,[
'default_image.*' => 'mimes:jpeg,bmp,png|max:2000'
]);
For more details: https://laravel.com/docs/5.4/validation#validating-arrays

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()%>");
<%}
}%>
}
});

How to populate Kendo Upload with previously uploaded files

I'm using the Kendo UI File Upload for MVC and it works great. On my edit page, I want to show the files that were previously uploaded from the Create page. For visual consistency, I would like to re-use the upload widget on my edit page so the user can use the "remove" functionality, or add additional files if they choose. Does the upload widget support this?
Thanks!
So, I realize this is question pretty old, but I recently figured out how to do this reliably. While the other answer on here will certainly display the files, it doesn't really wire it up to any of the events (specifically the "remove" event). Also, rather than manually setting all of this up, I figured I'd much rather have Kendo do all of the real dirty work.
Note, this only applies if your file upload is not set to autosync. If you use the auto upload feature, you can find examples in the Kendo documentation here: http://docs.kendoui.com/api/web/upload#configuration-files
So anyway, let's assume we have a file input that we've made into a Kendo Upload:
<input id="files" name="files" type="file" multiple="multiple" />
$(document).ready(function () {
var $upload = $("#files");
var allowMultiple = Boolean($upload.attr("multiple"));
$upload.kendoUpload({
multiple: allowMultiple,
showFileList: true,
autoUpload: false
});
}
Then, we just need to get the information about the files to our jQuery. I like to jam it into JSON strings in hidden fields, but you can do it however you want.
Here's an example using the Mvc HtmlHelpers and Newtonsoft's JSON.NET (I don't use Razor, but you should get the general idea):
if (Model.Attachments.Count > 0)
{
var files = Model.Attachments.Select(x => new { name = x.FileName, extension = x.FileExtension, size = x.Size });
var filesJson = JsonConvert.SerializeObject(files);
Html.Render(Html.Hidden("existing-files", filesJson));
}
Note, the format there is incredibly important. We're tying to match the structure of the JavaScript object that Kendo is expecting:
{
relatedInput : sourceInput,
fileNames: [{ // <-- this is the collection we just built above
name: "example.txt",
extenstion: ".txt",
size: 1234
}]
}
So, then all that's left to do is put it all together. Basically, we're going to recreate the onSelect function from Kendo's internal syncUploadModule:
$(document).ready(function () {
// setup the kendo upload
var $upload = $("#files");
var allowMultiple = Boolean($upload.attr("multiple"));
var upload = $upload.kendoUpload({
multiple: allowMultiple,
showFileList: true,
autoUpload: false
}).getKendoUpload();
// initialize the files
if (upload) {
var filesJson = $("[name$='existing-files']").val();
if (filesJson) {
var files = JSON.parse(filesJson);
var name = $.map(files, function (item) {
return item.name;
}).join(", ");
var sourceInput = upload._module.element.find("input[type='file']").last();
upload._addInput(sourceInput.clone().val(""));
var file = upload._enqueueFile(name, {
relatedInput : sourceInput,
fileNames : files
});
upload._fileAction(file, "remove");
}
}
});
And that's pretty much it!
I came up with a way to do this.
Basically, you need HTML that mimics what the Upload control generates, and you use a bit of JavaScript to hook each item up. I initially render the HTML as hidden, then after you initialize the Kendo Upload control, you append the HTML list to the parent container that Kendo creates.
This is my MVC view:
#if (Model.Attachments != null && Model.Attachments.Count > 0)
{
<ul id="existing-files" class="k-upload-files k-reset" style="display: none;">
#foreach (var file in Model.Attachments)
{
<li class="k-file" data-att-id="#file.Id">
<span class="k-icon k-success">uploaded</span>
<span class="k-filename" title="#file.Name">#file.Name</span>
<button type="button" class="k-button k-button-icontext k-upload-action">
<span class="k-icon k-delete"></span>
Remove
</button>
</li>
}
</ul>
}
and here is the JavaScript (note, it was generated from CoffeeScript):
var $fileList, $files, item, _fn, _i, _len;
$fileList = $("#existing-files");
if ($fileList.length > 0) {
$(".k-upload").append($fileList);
$files = $(".k-file");
_fn = function(item) {
var $item, fileId, filenames;
$item = $(item);
fileId = $item.data("att-id");
filenames = [
{
name: fileId
}
];
return $item.data("fileNames", filenames);
};
for (_i = 0, _len = $files.length; _i < _len; _i++) {
item = $files[_i];
_fn(item);
}
$fileList.show();
}
You can find the full write up on my blog where I go into depth on the topic. I hope this helps you!
Some additional searches gave me the answer I wasn't looking for - According to this and this, Telerik does not support pre-populating an upload widget with previously uploaded documents.
It has been added in the options since this question has been asked.
Check out http://docs.telerik.com/kendo-ui/api/web/upload#configuration-files
It only works in async mode.
Try this...
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("SaveFile", "Home")
.Remove("RemoveFile", "Home")
.AutoUpload(true))
.Files(files =>
{
foreach (var file in Model.FundRequest.Files)
{
files.Add().Name(file.Name).Extension(Path.GetExtension(file.Name)).Size((long)file.SizeKb * 1024);
}
}))
My Model has a reference to my "FundRequest" object that has a List of "File" objects, so I just loop through each "File" and add.
Check this out!
<script>
var files = [
{ name: "file1.doc", size: 525, extension: ".doc" },
{ name: "file2.jpg", size: 600, extension: ".jpg" },
{ name: "file3.xls", size: 720, extension: ".xls" },
];
$("#upload").kendoUpload({
async: {
saveUrl: "Home/Save",
removeUrl: "Home/Remove",
autoUpload: true
},
files: files
});
</script>
<input type="file" name="files" id="upload" />
Check this out, this is it.
Below code is copied and adapted from kendo-ui documentation:
<div id="example">
<div>
<div class="demo-section">
<input name="files" id="files" type="file" />
</div>
</div>
<script>
$(document).ready(function () {
if (sessionStorage.initialFiles === undefined) {
sessionStorage.initialFiles = "[]";
}
var initialFiles = JSON.parse(sessionStorage.initialFiles);
$("#files").kendoUpload({
showFileList: true,
multiple: true,
async: {
saveUrl: "save",
autoUpload: false,
batch: true
},
files: initialFiles,
success: onSuccess
});
function onSuccess(e) {
var currentInitialFiles = JSON.parse(sessionStorage.initialFiles);
for (var i = 0; i < e.files.length; i++) {
var current = {
name: e.files[i].name,
extension: e.files[i].extension,
size: e.files[i].size
}
if (e.operation == "upload") {
currentInitialFiles.push(current);
} else {
var indexOfFile = currentInitialFiles.indexOf(current);
currentInitialFiles.splice(indexOfFile, 1);
}
}
sessionStorage.initialFiles = JSON.stringify(currentInitialFiles);
}
});
</script>
</div>

Load JavaScript when partial is called via ColorBox?

It seems when loading a Razor partial view via ColorBox (not using an iframe), the JavaScript libraries do not initialize properly or it is an artifacte of the partial. If I include the libraries in the parent page, the JavaScript function runs inside the partial jsut fine. I don't see any errors coming from the browser when the library is in the partial, but it is not working. If I move the library (in this case fileuploader.js) outside of the partial and keep the function in the partial it works fine.
Example:
<script src="#Url.ContentArea("~/Scripts/plugins/ajaxUpload/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script>
$(function () {
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
.....
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
....
}
}
});
});
<script>
You may want to check whether there are duplicate references to the JavaScript libraries you are using (one in the parent and one in the partial).
This is a common issue and it will not raise any errors whatsoever, but will stop your JavaScript code from executing.
I think this is a time line problem.Before the "Partial View" load(or appending the div) JavaScript try to bind it and fail.So it cannot find a element which is in your Partial View document.I had a problem with like this with "ColorBox".I have found a solution for this problem.For example : When you call GET or POST method ,after the query put a control point like this .For example for binding "colorbox" :
function getMyPartial(partialname) {
var resultDiv = document.getElementById("content");
$.ajax({
type: "GET",
url: partialname,
async: false,
success: function (data) {
resultDiv.innerHTML = "";
resultDiv.innerHTML = data.toString();
}
});
var indd = 0; //This is Control Point
if (partialname == "YourPartialName") {
var yourelementinpartial= document.getElementById("example");
while (!yourelementinpartial) {
indd++;
}
$(".group4").colorbox({ rel: 'group4' }); //binding point
}
}
At the control point, if any of the element in your PartialView document has found it will bind.

AntiForgeryToken not being received when using plupload in form submission

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.

Resources