how to get file details of uploaded file in extJS - javascript

how to get file details of uploaded file in extJS
I am using file upload and I need to first conveert into Grid and then sumbit.
for grid conversion I have to take all files details like this :
File {
webkitRelativePath: "",
lastModifiedDate: Tue Jul 14 2009 11:02:31 GMT+0530 (India Standard Time),
name: "file.xlsx",
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
size: 780831
}
and here I am converting this to excell..
function handleFileSelect(evt){
var files = evt.target.files;
SessionConstant.uploadFileName = files[0].name;
var xl2json = new ExcelToJSON();
xl2json.parseExcel(files[0]);
// Next code
}
function ExcelToJSON () {
this.parseExcel = function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result;
var workbook = XLSX.read(data, {
type: 'binary'
});
var uploadata = [];
workbook.SheetNames.forEach(function(sheetName) {
var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var json_object = JSON.stringify(XL_row_object);
console.log(JSON.parse(json_object));
uploadata.push(JSON.parse(json_object));
jQuery( '#xlx_json' ).val( json_object );
});
var uploadData = uploadata;
};
reader.onerror = function(ex) {
console.log(ex);
};
reader.readAsBinaryString(file);
};
};
so this code when I am doing by using this
{
text:'Upload',
handler : function(){
var x = document.createElement("INPUT");
x.setAttribute("type", "file");
x.setAttribute("id","upload");
document.body.appendChild(x);
document.getElementById('upload').addEventListener('change', handleFileSelect, false);
document.getElementById('upload').click();
},
}
This is working fine.
Now If I want to implement same thing fileupload in extJS so I can submit my form :
{
xtype: 'filefield',
cls:'common-fileupload',
itemId:'fileUploadId',
clearOnSubmit:false,
width:300,
labelWidth : '0',
name: 'myFile',
buttonConfig: {
text: 'Browse',
height : 30
},
listeners: {
change: function(fld, value) {
var newValue = value.replace(/C:\\fakepath\\/g, '');
fld.setRawValue(newValue);
this.up().submit({
url: 'url',
method: 'POST',
success: function (form, action) {
},
failure: function (form, action) {
},
error: function (form, action) {
}
});
}
},
style:'margin-right:10px'
}
So In Change method How to get files details so I can write my handleFileSelect method.
Any idea willbe helpfull.

For the classic framework, following way should work:
listeners: {
change: function(fld, value) {
let file = fld.fileInputEl.dom.files[0];
}
},

Related

Import from Excel with AngularJS

I am trying to import the Excel in to the ui-grid. I am trying to use the js xlsx library. I can convert the xlsx in to JSON but I am not sure how I can populate the xlsx in to the ui-grid. Below is the ui-grid:
$scope.samplesGridOptions = {
enableColumnResizing: true,
enableRowSelection: true,
multiSelect: false,
enableGridMenu: true,
enableCellEditOnFocus: true,
columnDefs: [
{ field: 'externalID', displayName: 'External ID' },
{ field: 'apexLotNum', displayName: 'APEX Lot' },
{
field: 'chamberName',
displayName: 'Chamber Name',
editType: 'dropdown',
editableCellTemplate: 'ui-grid/dropdownEditor',
enableCellEdit: true, editDropdownOptionsArray: $scope.chamberNameList,
editDropdownIdLabel: 'value',
editDropdownValueLabel: 'value'
}
],
gridMenuCustomItems: [],
onRegisterApi: function (gridApi) {
$scope.samplesGridAPI = gridApi;
$scope.samplesGridOptions.data = $scope.virtualSampleList;
}
};
I am trying to use the the js-xlsx library below to parse the excel file loaded. But not sure how to push that into the ui-grid, new to Javascripting and the libraries.
$scope.ParseExcelDataAndSave = function () {
var file = $scope.SelectedFileForUpload;
if (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
var sheetName = workbook.SheetNames[0];
var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var jsonData = JSON.stringify(excelData);
if (jsonData.length > 0) {
**//Here I am not sure how can I populate the ui-grid from the JSON**
}
else {
$scope.Message = "No data found";
}
}
reader.onerror = function (ex) {
console.log(ex);
}
reader.readAsBinaryString(file);
}
}
This is the example given in the js-xlsx documentation:1
$http({
method:'GET',
url:'https://sheetjs.com/pres.xlsx',
responseType:'arraybuffer'
}).then(function(response) {
var wb = XLSX.read(response.data, {type:"array"});
var d = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
$scope.data = d;
}, function(err) { console.log(err); });
For files use:
function fileToArrayPromise(file) {
var promise = $q(function(resolve, reject) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
resolve(data);
}
reader.onerror = function (ex) {
reject(ex);
}
reader.readAsArrayBuffer(file);
})
return promise;
}
fileToArrayPromise(file)
.then(function(data) {
var wb = XLSX.read(data, {type:"array"});
var d = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
$scope.data = d;
}, function(err) {
console.log(err);
throw err;
});
For more information, see
SheetJS Demos - AngularJS

DataTable to Excel Word and PDF

The code below show only 10 records because of my filters
m.getData = function (options, callback) {
table = $('#auditTrailTable').DataTable();
var info = table.page.info();
options.RecordsToSkip = info.start;
options.RecordsToTake = info.length;
var data = table.ajax.params();
options.SortDirection = data.order[0].dir;
options.ColumnName = data.columns[data.order[0].column].data;
var paramDTO = {
param: options,
searchValue: '',
dateFrom: m.filterDateFrom(),
dateTo: m.filterDateTo()
};
var url = '/AuditTrail/Find';
knock.AjaxBlockElement(paramDTO, url, '', function (result) {
if (result.Data != undefined) {
callback(result);
}
});
};
The code below is my function to export the current page shown to excel only
m.exportToExcel = function () {
var oTable = $('#auditTrailTable').DataTable();
$.fn.DataTable.Export.excel(oTable, {
filename: 'AuditTrail_Export',
title: 'WebSOA Audit Trail',
message: '',
header: ['Activity', 'Name', 'Username', 'Timestamp'],
fields: ["Activity", "Name", "Username", "TimestampString"]
});
}
;
My target is to export all records that aren't shown to excel/pdf and word but I only want to show is the current page with 10 records. Meaning all records from Page 2 up to the last page will be exported.

Mistake from cordova.js after getting file from camera

We got file, it lies in cache, and i see it in Console
But when i tried to save it and send, i got this mistakes from cordova.js
Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
Uncaught TypeError: Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
Error in Success callbackId: File1917405046 : TypeError: Wrong type for parameter "newName" of Entry.copyTo: Expected String, but got Number.
ngCordova installed and injected
Cordova is updated
and i can't send my file, please help me
that's my code in controller
$scope.attachPhoto = function() {
$ionicActionSheet.show({
buttons: [
{ text: '<i class="icon ion-android-image"></i>Перейти в галерею' },
{ text: '<i class="icon ion-android-camera"></i> Сделать фото' }
],
cancelText: 'Cancel',
cancel: function() {
},
buttonClicked: function(index) {
var options = {
destinationType : Camera.DestinationType.FILE_URI,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : false,
encodingType: Camera.EncodingType.JPEG,
popoverOptions: CameraPopoverOptions
};
$cordovaCamera.getPicture(options).then(function(imageData) {
onImageSuccess(imageData);
console.log(imageData);
function onImageSuccess(fileURI) {
createFileEntry(fileURI);
console.log(fileURI);
}
function createFileEntry(fileURI) {
window.resolveLocalFileSystemURL(fileURI, copyFile, fail);
console.log(fileURI);
}
function copyFile(fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var imgBlob = new Blob([ this.result ], { type: "image/jpeg" } );
$scope.attach = true;
$scope.file = imgBlob;
};
reader.readAsArrayBuffer(file);
});
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
12345,
onCopySuccess,
fail
);
}, fail);
}
function onCopySuccess(entry) {
$scope.$apply(function () {
$scope.images.push(entry.nativeURL);
$scope.attach = true;
$scope.sendPhoto();
});
}
function fail(error) {
console.log("fail: " + error.code);
}
}, function(err) {
console.log(err);
});
console.log(options);
return true;
}
})
};
$scope.sendPhoto = function() {
var data = {
file: $scope.file
}
console.log(data);
var fd = new FormData(data);
xhr = new XMLHttpRequest();
xhr.open("POST", "http://eatmeet.ru/serv.php");
xhr.setRequestHeader('Content-Type', 'application/upload');
xhr.send(fd);
}
Try to parse a string as fileName, not a number. Please check the file documentation.
The correct syntax is:
fileEntry.copyTo(parent [DirectoryEntry], newName [DOMString], successCallback [Function], errorCallback [Function]);
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(fileSystem2) {
fileEntry.copyTo(
fileSystem2,
"12345",
onCopySuccess,
fail
);
}, fail);

Use a prepended image as wallpaper using Mozactivity Firefox OS

I want to fetch an image from the web and set it as wallpaper on the Firefox OS device.
So far I've tried two approaches,
$(document).on( 'click', '#share-image', function() {
walp = new Image()
walp.onload = function () {
var walCanvas = document.createElement('canvas');
walCanvas.width = walp.width;
walCanvas.height = walp.height;
var walCtx = walCanvas.getContext('2d');
walCtx.drawImage(walp,0,0);
walCanvas.toBlob( function (walBlob) {
var Activitiy = new MozActivity({
name: 'share',
data: {
type: 'image/*',
number: 1,
blobs: [walBlob]
}
});
});
};
walp.src = image; //image is the link to jpeg.
});
And this one...
var shareImage = document.querySelector("#share-image"),
imgToShare = document.querySelector('#prependedImage');
alert(imgToShare);
if (shareImage && imgToShare) {
shareImage.onclick = function () {
if(imgToShare.naturalWidth > 0) {
// Create dummy canvas
var blobCanvas = document.createElement("canvas");
blobCanvas.width = imgToShare.width;
blobCanvas.height = imgToShare.height;
// Get context and draw image
var blobCanvasContext = blobCanvas.getContext("2d");
blobCanvasContext.drawImage(imgToShare, 0, 0);
// Export to blob and share through a Web Activitiy
blobCanvas.toBlob(function (blob) {
new MozActivity({
name: "share",
data: {
type: "image/*",
number: 1,
blobs: [blob]
}
});
});
}
else {
alert("Image failed to load, can't be shared");
}
};
}
Both work for a locally saved image but don't work for the image that is fetched from a remote location.
I've also tried following approaches.
var pre = '<img width="100%" data-l10n-id="prependedImage" id="prependedImage" src="'+image+'" />';
$('#image1').prepend(pre);
and
$('#prependedImage').attr('src',image);
Both work, but neither presents the wallpaper menu unless it is a locally saved image.
I'm new to javascript and would appreciate an answer which explains what's wrong with code samples.
Thanks.
Can you try something like:
var xhr = new XMLHttpRequest({
mozSystem: true
});
xhr.open("GET", "http://25.media.tumblr.com/4751d1eccf9311ee0e05bdff819a7248/tumblr_n2yxzxzxr81rsg8blo1_250.png", true);
xhr.responseType = "blob";
xhr.onload = function () {
//sample activity
var activity = new MozActivity({
name: "share",
data: {
type: "image/*",
number:1,
blobs: [this.response],
filenames:["wallpapertest.png"]
},
});
};
xhr.onerror = function () {
alert("Error with System XHR");
};
xhr.send();
You will also need to set the app as privileged and add the systemxhr permission in the manifest:
"permissions": {
"systemXHR": {}
},
"type": "privileged"

How can I remove a whole IndexedDB database from JavaScript?

How can one remove a whole IndexedDB database from JavaScript, as opposed to just an object store? I'm using the IndexedDB shim, which may use WebSQL as its backend.
I'd mainly like to know how to do this for the PhantomJS (headless) browser, although Chrome, Safari (on iPad) and IE10 are other important browsers.
As far as I can tell, one should use indexedDB.deleteDatabase:
var req = indexedDB.deleteDatabase(databaseName);
req.onsuccess = function () {
console.log("Deleted database successfully");
};
req.onerror = function () {
console.log("Couldn't delete database");
};
req.onblocked = function () {
console.log("Couldn't delete database due to the operation being blocked");
};
I can confirm that it works with PhantomJS 1.9.0 and Chrome 26.0.1410.43.
I found that the following code works OK but to see the DB removed in the Chrome Resources Tab I have had to refresh the page.
Also I found I had problems with the Chrome debug tools running while doing transactions. Makes it harder to debug but if you close it while running code the code seems to work OK.
Significant also is to set a reference to the object store when opening the page.
Obviously the delete part of the code is in the deleteTheDB method.
Code derived from example provided by Craig Shoemaker on Pluralsight.
var IndDb = {
name: 'SiteVisitInsp',
version: 1000,
instance: {},
storenames: {
inspRecords: 'inspRecords',
images: 'images'
},
defaultErrorHandler: function (e) {
WriteOutText("Error found : " + e);
},
setDefaultErrorHandler: function (request) {
if ('onerror' in request) {
request.onerror = db.defaultErrorHandler;
}
if ('onblocked' in request) {
request.onblocked = db.defaultErrorHandler;
}
}
};
var dt = new Date();
var oneInspRecord =
{
recordId: 0,
dateCreated: dt,
dateOfInsp: dt,
weatherId: 0,
timeArrived: '',
timeDeparted: '',
projectId: 0,
contractorName: '',
DIWConsultant: '',
SiteForeman: '',
NoOfStaffOnSite: 0,
FileME: '',
ObservationNotes: '',
DiscussionNotes: '',
MachineryEquipment: '',
Materials: ''
};
var oneImage =
{
recordId: '',
imgSequence: 0,
imageStr: '',
dateCreated: dt
}
var SVInsp = {
nameOfDBStore: function () { alert("Indexed DB Store name : " + IndDb.name); },
createDB: function () {
openRequest = window.indexedDB.open(IndDb.name, IndDb.version);
openRequest.onupgradeneeded = function (e) {
var newVersion = e.target.result;
if (!newVersion.objectStoreNames.contains(IndDb.storenames.inspRecords)) {
newVersion.createObjectStore(IndDb.storenames.inspRecords,
{
autoIncrement: true
});
}
if (!newVersion.objectStoreNames.contains(IndDb.storenames.images)) {
newVersion.createObjectStore(IndDb.storenames.images,
{
autoIncrement: true
});
}
};
openRequest.onerror = openRequest.onblocked = 'Error'; //resultText;
openRequest.onsuccess = function (e) {
//WriteOutText("Database open");
IndDb.instance = e.target.result;
};
},
deleteTheDB: function () {
if (typeof IndDb.instance !== 'undefined') {
//WriteOutText("Closing the DB");
IndDb.instance.close();
var deleteRequest = indexedDB.deleteDatabase(IndDb.name)
deleteRequest.onblocked = function () {
console.log("Delete blocked.");
}
deleteRequest.onerror =
function () {
console.log("Error deleting the DB");
//alert("Error deleting the DB");
};
//"Error deleting the DB";
deleteRequest.onsuccess = function () {
console.log("Deleted OK.");
alert("*** NOTE : Requires page refresh to see the DB removed from the Resources IndexedDB tab in Chrome.");
//WriteOutText("Database deleted.");
};
};
}
}

Categories

Resources