How do I fix this dropzone.js layout issue - javascript

I am working on a project and started using dropzone.js, and then was moved to another task, and when I returned to this task, a former co-worker had made some modifications..
Its prob an easy issue, but I am needing to learn - he created some TABLES which I dont want, I just want to be able to display the VAR data on items I create and control via css.
My issue, is I am lost on how to use his functions in the and make them be more "html" based so I can assign my css to it.
I´m trying dropzone.js and want the layout like on this page dropzonejs.com or this Work with DropzoneJS
<script>
var files = [];
var total_count = 0;
var processing = false;
function deleteFile(fileid) {
var file = files[fileid];
total_count -= file.count;
files[fileid] = null;
document.getElementById('dr_total').innerHTML = total_count;
var row = document.getElementById('dr_'+fileid);
row.parentNode.removeChild(row);
dz_deleteRemoteFile(file.file);
}
function checkout() {
if (processing) {
return true;
}
if (files.length < 1) {
alert('Please upload files');
return false;
}
processing = true;
document.getElementById('btnCheckout').innerHTML = 'Processing...';
var result = dz_addOrder();
if (!result) {
document.getElementById('btnCheckout').innerHTML = 'Checkout';
processing = false;
}
}
</script>
<script language="javascript" src="dropzone.js"></script>
<script>
Dropzone.options.myDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 200, // MB
//acceptedFiles: "application/csv,text/csv,application/vnd.ms-excel",
clickabke: false,
dictDefaultMessage: 'Drag or Select files to Upload',
method: "POST",
uploadMultiple: false,
accept: function(file, done) {
if (file.name.substring(file.name.length-3).toLowerCase() != 'csv') {
done('ERROR: Invalid file type, only CSV files allowed.');
} else {
done();
}
},
error: function(file, errorMessage, xhr) {
alert('ERROR: '+file.name+' '+errorMessage);
},
success: function(file, message) {
var ret = JSON.parse(message);
if (ret.status == "ERROR") {
alert('ERROR: '+file.name+' '+ret.message);
return false;
}
var obj = {
file:ret.file,
name:file.name,
count:ret.count
};
files.push(obj);
total_count += ret.count;
var table = document.getElementById('dr_files');
var row = table.insertRow(-1);
row.id = 'dr_'+(files.length-1);
row.insertCell(0).innerHTML = file.name;
row.insertCell(1).innerHTML = ret.count;
row.insertCell(2).innerHTML = '<button class="verifybuttonred" onclick="deleteFile('+(files.length-1)+')">delete</button>';
document.getElementById('dr_total').innerHTML = total_count;
var dz = this;
setTimeout(function(){
dz.removeFile(file);
},1000,dz);
}
};
</script>
<link rel="stylesheet" type="text/css" href="basic.css">
<link rel="stylesheet" type="text/css" href="dropzone.css">
<body>
<form action="data_hygiene/upload.php" id="myDropzone" class="dropzone" enctype="multipart/form-data" method="post">
<input type="hidden" name="clientid" id="clientid" value="0">
</form>
<div id="dr_filelist">
<br/><br/><br/><table border="1" cellpadding="5" cellspacing="5" bordercolor="#000000" width="100%" id="dr_files">
<tr><th width="70%">File</th><th width="15%">Count</th><th width="15%">Options</th></tr>
<tr><td></td><td></td><td></td></tr>
</table>
<table border="1" cellpadding="5" cellspacing="5" bordercolor="#000000" width="100%" id="dr_files">
<tr><th width="70%">Total</th><th width="15%"><div id="dr_total"></div></th><th width="15%"><button class="buttongreen" id="btnCheckout" onClick="checkout();">Checkout</button></th></tr>
</table>
So you will in near the end, he has the :
var table = document.getElementById('dr_files');
var row = table.insertRow(-1);
row.id = 'dr_'+(files.length-1);
row.insertCell(0).innerHTML = file.name;
row.insertCell(1).innerHTML = ret.count;
row.insertCell(2).innerHTML = '<button class="verifybuttonred" onclick="deleteFile('+(files.length-1)+')">delete</button>';
this is what I am wanting to remove from a TABLE layout...
This is how it currently looks - (which is crap)
enter image description here

Related

Check Mime Type in jQuery before file upload after changing the extension

I have been trying to implement various logics found on the internet. But the issue is that if I change the extension of any file it shows Okay. My code is as below:
'use strict';
$("#myfiles").on('change',function(){
var files = $('#myfiles').get(0).files;
if (files.length > 0) {
var file = files[0];
var fileReader = new FileReader();
fileReader.onloadend = function (e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = '';
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
alert(header);
var type = 'unknown';
switch (header) {
case '89504e47':
type = 'image/png';
break;
case '47494638':
type = 'image/gif';
break;
case 'ffd8ffe0':
case 'ffd8ffe1':
case 'ffd8ffe2':
type = 'image/jpeg';
break;
case '25504446':
type = 'application/pdf';
break;
}
//if(type=='image/jpeg') { alert('Its JPEG/JPG'); } else { alert('Its Not'); }
//alert(type);
if (type!=='image/png' && type!=='image/gif' && type!=='image/jpeg' && type!=='application/pdf' ) {
alert("File Type Not Allowed");
} else {
$('#myfile_mydrive').fileupload({
downloadTemplateId: 'template-download-gallery',
uploadTemplateId: 'template-upload-gallery',
paramName: 'files[]',
url: 'mydrive-upload.php',
dataType: 'json',
autoUpload: true,
maxNumberOfFiles: 10,
acceptFileTypes: /(\.|\/)(pdf|doc|docx|xls|ppt|zip|gif|jpe?g|png)$/i
});
}
};
fileReader.readAsArrayBuffer(file);
}
});
So I implemented the code above. But it shows okay for once or twice then it uploads the file even after showing that file type is not supported.
Atlast found the work around. If anybody needs for mime check in blueimp jquery upload
$('#myfile_mydrive').fileupload({
add: function(e, data) {
var uploadErrors = [];
var control = document.getElementById("myfiles");
control.addEventListener("change", function(event) {
var files = event.target.files[0];
for (var i = 0; i < files.length; i++) {
console.log("Filename: " + files[i].name);
console.log("Type: " + files[i].type);
console.log("Size: " + files[i].size + " bytes");
}
}, false);
var files = event.target.files[0];
var fileReader = new FileReader();
fileReader.onload = function(e) {
var int32View = new Uint8Array(e.target.result);
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
if(header!=='89504e47' && header!=='47494638' && header!=='ffd8ffe0' && header!=='ffd8ffe1' && header!=='ffd8ffe2' && header!=='25504446') { // Check for jpg/jpeg/png/gif/pdf
alert("File Type Mismatch");
return;
} else {
data.submit();
}
};
fileReader.readAsArrayBuffer(files);
},
downloadTemplateId: 'template-download-gallery',
uploadTemplateId: 'template-upload-gallery',
paramName: 'files[]',
url: 'mydrive-upload.php',
dataType: 'json',
autoUpload: false,
maxNumberOfFiles: 10,
acceptFileTypes: /(\.|\/)(pdf|gif|jpe?g|png)$/i,
});
The HTML part of my code
<div id="myfile_mydrive" class="fileupload">
<div class="fileinput-button btn btn-success btn-sm">
<i class="fa fa-paperclip"></i>
<span>Browser Files </span >
<input type="file" id="myfiles" name="myfiles">
</div>
<table role="presentation" class="table table-striped">
<tbody class="files"></tbody>
</table>
</div>
As you can see the issue I faced earlier was:-
'on' change was not firing up the '.fileupload' function.
The 'mime' check was not functioning properly as the values of 'mime' results were not getting cleared.
Therefore, you may see the workaround is 'add' function under the 'fileupload'
Hope that clarifies any doubt about the solution.

How to access to specific row of excel file using Javascript

I am reading random row of large Excel file using Javascript. But it is taking some time for example when I am working with 300.000 row data in excel file. I need fast way.
<body>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="Upload()" />
<!-- <input type="button" id="upload" value="Random" onclick="ProcessExcel()" /> -->
<hr />
<h1 id="exc">Hello</h1>
<p id="her"></p>
<p id="limm"></p>
<div id="dvExcel"></div>
<script type="text/javascript">
// var gl_ex = "";
function Upload() {
//Reference the FileUpload element.
var fileUpload = document.getElementById("fileUpload");
//Validate whether File is valid Excel file.
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xls|.xlsx)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
//For Browsers other than IE.
if (reader.readAsBinaryString) {
reader.onload = function (e) {
ProcessExcel(e.target.result);
};
reader.readAsBinaryString(fileUpload.files[0]);
} else {
//For IE Browser.
reader.onload = function (e) {
var data = "";
var bytes = new Uint8Array(e.target.result);
for (var i = 0; i < bytes.byteLength; i++) {
data += String.fromCharCode(bytes[i]);
}
ProcessExcel(data);
// gl_ex = data;
//alert("Uploaded.");
};
reader.readAsArrayBuffer(fileUpload.files[0]);
}
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid Excel file.");
}
};
function ProcessExcel(data) {
//var data = "";
//data = gl_ex;
//Read the Excel File data.
var workbook = XLSX.read(data, {
type: 'binary'
});
//Fetch the name of First Sheet.
var firstSheet = workbook.SheetNames[0];
//Read all rows from First Sheet into an JSON array.
var excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);
var len = excelRows.length;
var rand_num = Math.floor((Math.random() * len) + 1);
document.getElementById("her").innerHTML = rand_num;
document.getElementById("limm").innerHTML = len;
document.getElementById("exc").innerHTML = excelRows[rand_num-1].Name;
};
</script>
</body>
As in example shown I am reading random row from Excel file. I think javascript is reading whole excel file sequentially. Can I read specific row data in faster way?

Ajax post has previous data

This is driving me crazy. I know I am doing something wrong but what? The problem is I am getting previous data in my ajax call when I post it to php.
Story: I click upload button which calls JavaScript loadme() where i am cleaning the input type file element. I then select file/files and click upload which calls doit() which internally calls uploadFiles(). UploadFiles makes an array with loaded images and post it to the php file through ajax.
I have tried plain javascript and jquery to clean file input element and php to set post values to null after using it, but still i am getting the previous values.
The form
<form id="theform" method="post" action="" enctype="multipart/form-data" target="multifile">
<input type="hidden" id="folderpath" name="folderpath" value="<?=htmlspecialchars($path)?>">
<input name="upfiles[]" id="upfiles" type="file" multiple="" />
</form>
Javascript
async function doit(){
//some code
uploadFiles();
}
function loadmeup(){
$('upfiles').value = '';
$('uploadbox').show();
}
function closeupload(){
$('uploadbox').hide();
}
var masterFileArray = [];
var left_loaded_count = 0;
var progress = 0;
function uploadFiles() {
var files = document.getElementById("upfiles").files;
var path = document.getElementById('folderpath').value;
var numOfFiles = files.length;
alert(numOfFiles);
if (files && numOfFiles>0) {
for (var i = 0, f; f = files[i]; i++) {
if(checkExtension(f.name) && checkSize(f.size)){
progress = i+1/numOfFiles;
var r = new FileReader();
r.onload = (function (f) {
return function (e) {
var contents = e.target.result;
masterFileArray.push({name:f.name, contents: contents, type:f.type, size:f.size});
console.log(f.name);
left_loaded_count -= 1;
if(left_loaded_count == 0)
{
var filesarray = null;
filesarray = JSON.stringify(masterFileArray);
console.log("after stringify: "+filesarray.length);
new Ajax.Request('upload_do.php', {
method: 'post',
parameters: {files: filesarray, folderpath:path},
onSuccess: function(transport){
var response = transport.responseText;
parent.notify(response);
closeupload();
get_listview(currlist,sort);
}
});
}
};
})(f);
left_loaded_count += 1;
r.readAsDataURL(f);
}
else{
alert('Invalid file extension or size ' + f.name);
if(progress==0)
location.reload();
}
}
} else {
alert('Failed to load files');
closeupload();
}
}
PHP
try{
$error = null;
$files = json_decode($_POST['files'],true);
$numFiles = 0;
foreach($files as $file){
$output = $reso->writeUpload($file['contents'], $file['name']);
$numFiles++;
}
}
catch (Exception $ex){
$error = $ex->getMessage();
$GLOBALS['log']->log($error);
}
isset($_POST['files'])? $_POST['files'] = null: '';
if (!is_null($error))
echo _($error);
else
echo _($numFiles.' file'.(($numFiles > 1) ? 's' : '').' successfully
uploaded');

How do I upload file on an aspx page without using webforms?

I have an aspx page which already has a code for uploading file using "asp:FileUpload" and webform. On a different section of page, I want to add the functionality for a user to upload file. But i do not want to use webforms or "asp:fileupload".
So, I created an HTML file that i inject as an iframe inside a div tag on the aspx.
<div id="iUploadDoc" style="height:50px;">
<iframe name='FileUpload' id='FileUpload' class='iUploadFrame' width='100%' frameborder='0' border='0'src='DocUpload.htm'></iframe></div>
I set the EnablePageMethods to true.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
And inside the HTML I made a form and with input type file.
<form method="POST" action="DocDetail.aspx.cs" id="docUpload" enctype="multipart/form-data">
<div>
<label for="fileUpload" class="inputLabel">Upload File</label>
<input type="file" id="fileUpload" name="files"/>
</div>
</form>
<div id="progUpload" style="display: none;">
<p class="uploadBox">Uploading...</p>
</div>
<span id= "selectedFile" style="display: none;"></span><span id="fileName" style="display: none;"></span>
Now, I dont know what to put in the "action" param of form.
First on the iframe, below is the script i wrote:
window.onload = load;
function uploadDocFile() {
var prog = document.getElementById("progUpload");
prog.style.cssText = 'display: block;';
var x = document.getElementById("fileUpload");
var txt = "";
var filePath = "";
var fileName = "";
if (x.value == "") {
txt += "Select a file.";
document.getElementById("selectedFile").innerHTML = txt;
} else {
filePath = x.value;
fileName = filePath.replace(/^.*[\\\/]/, '');
txt += "<br>Selected file: ";
document.getElementById("selectedFile").innerHTML = txt;
document.getElementById("fileName").innerHTML = fileName;
}
var formInfo = document.getElementById("docUpload");
document.getElementById("docUpload").style.display = "none";
window.parent.getFormData(formInfo, x ,x.value, fileName);
}
function load() {
var e = document.getElementById("fileUpload");
//var formInfo = document.getElementById("docUpload");
//fakeClick();
e.onchange = function () {
uploadDocFile();
}
}
Then on the parent page, below is the script i wrote.
DocUpload.prototype.uploadFileDoc= function (formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type) {
//blacklitsType is an array of types of file (similarly for blacklistExt) that should not be allowed to upload
if (indexOf.call(blackListType, type) < 0 && indexOf.call(blackListExt, extension) < 0) {
var idParams = { OiD: ordId, pID: pId, QID: qId }
var files = uploadedFile.files;
var fileEntries = [];
for (j = 0, len1 = files.length; j < len1; j++) {
file = files[j];
if (file.getAsEntry) {
entry = file.getAsEntry();
} else if (file.webkitGetAsEntry) {
entry = file.webkitGetAsEntry();
}
if (entry) {
isFyl = entry.isFile;
if (!isFyl) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileItem = file.getAsFile();
fileEntries.push(fileItem);
}
} else if (!file.type && file.size % 4096 === 0) {
alert("You can not upload a folder. Uploading files (if present).");
} else {
fileEntries.push(file);
}
}
PageMethods.UploadDocument(fileEntries[0], idParams, function (res) {
if (res == true) {
alert("File uploaded successfully.");
} else {
alert("File upload failed.");
}
}, function (err) {
alert("ERROR: " + err._message);
});
} else {
window.alert('You cannot upload incorrect file types.');
}
return;
};
DocUpload.prototype.getFormData = function (formInfo, uploadedFile, fileInfo, nameInfo) {
var currDate, extension, lastModifiedDate, name, nameArr, size, type;
currDate = new Date();
lastModifiedDate = currDate;
type = '';
size = 512;
name = nameInfo;
nameArr = name.split(".");
extension = nameArr[nameArr.length - 1];
DocUpload.prototype.uploadFileDoc(formInfo, uploadedFile, fileInfo, lastModifiedDate, name, extension, size, type);
};
window.getFormData = DocUpload.prototype.getFormData;
The transfer of attributes of form from iframe to parent page work just fine. But how should i post it as file using PageMethod. Below is the page method in my code behind:
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = false)]
public static bool UploadDocument(HttpPostedFileBase uploadedFile,IdParams idParams) {
bool err = false;
try{
//code
err= true;}
catch(Exception ex){err = false;}
return err;
}
No matter how much tried, either I keep getting error regarding HTTPPostedFileBase or Serialization of child not allowed.Below are only some of the errors i keep getting (not at the same time):
No parameterless constructor System.Web.HttpPostedFileBase aspx, OR
The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter
What should i do?

Knockout array binding works only once

I am working on a file upload code which at the moment works only in Chrome and Firefox. It allows users to drag and drop files which get uploaded. The upload progress is shown in a grid.
Here is the html
<form id="fileUploadForm" action="home/upload" method="post" enctype="multipart/form-data">
<input type="file" id="fileselect" name="files" multiple="multiple" />
<div id="filedrag">Drop files here</div>
<button type="submit" id="submitbutton">Upload Files</button>
</form>
<table class="datatable" data-bind="visible:files().length>0">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Upload progress</th>
<th>Progress bar</th>
</tr>
</thead>
<tbody data-bind="foreach:files">
<tr>
<td data-bind="text:name"></td>
<td data-bind="text:status"></td>
<td data-bind="text:percentUploaded"></td>
<td>
<progress max="100" data-bind="attr: {value:percentUploaded}"></progress>
<span data-bind="text:$root.files().length"></span></td>
</tr>
</tbody>
</table>
<pre data-bind="text: ko.toJSON($data.files, null, 2)"></pre>
And here is the JavaScript:
var File = function (f) {
this.name = f.name;
this.type = f.type;
this.size = f.size;
this.lastModified = f.lastModifiedDate.toDateString();
this.status = ko.observable(f.status);
this.percentUploaded = ko.observable(0);
};
var ViewModel = function () {
var self = this,
maxFileSize = 5000000,
onFileSelecting = function (e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
},
onFileSelected = function (e) {
onFileSelecting(e);// cancel event and hover styling
var files = e.target.files || e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
var validationResult = validate(f);
f.status = validationResult || 'Uploading';
self.addFile(f);
uploadFile(f);
}
},
validate = function (f) {
if (f.size > maxFileSize)
return 'Too large, should be less than 5MB';
if (f.type.indexOf("text") != 0)
return 'Wrong file type';
},
uploadFile = function (f) {
var file = self.files()[0];
var fd = new FormData();
fd.append("files", f, f.name);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", function (e) {
file.status("Uploaded " + parseInt(e.loaded / e.total * 100) + "%");
file.percentUploaded(parseInt(e.loaded / e.total * 100));
}, false);
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4) {
file.status((xhr.status == 200 ? "success" : "failure"));
}
};
xhr.open("POST", $("#fileUploadForm")[0].action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(fd);
};
self.files = ko.observableArray();
self.addFile = function (f) { self.files.unshift(new File(f)); };
$(document).ready(function () {
if (window.File && window.FileList && window.FileReader) {
var fileSelector = $("#fileselect"),
fileDragArea = $("#filedrag"),
submitButton = $("#submitbutton");
fileSelector.change(onFileSelected);
var xhr = new XMLHttpRequest();
if (xhr.upload) {
filedrag.addEventListener("dragover", onFileSelecting, false);
filedrag.addEventListener("dragleave", onFileSelecting, false);
filedrag.addEventListener("drop", onFileSelected, false);
filedrag.style.display = "block";
submitbutton.style.display = "none";
fileSelector.hide();
}
}
});
};
var model = new ViewModel();
ko.applyBindings(model);
When I drag and drop a set of files, everything works fine. However, when I drag and drop another set, the files array gets updated, but the grid does not show additional rows.
However, everything works fine when I take out this piece of HTML5 mark up:
<progress max="100" data-bind="attr: {value:percentUploaded}"></progress>
I have created the fiddle (http://jsfiddle.net/9aJtG/1) but it has other problems - 1) The drag and drop on fiddle just opens up the file (not sure why) 2) on dropping the files the files get submitted, but there is no server side code which can work with JSFiddle form posting
I have tried with progress bar in another example, which does not have this problem http://jsfiddle.net/bxfXd/800/
Any ideas?
Many thanks!

Categories