javascript file object storing/retrieve in cookies - javascript

I am storing File list in cookies so that if I navigate to another page and come back to this page, I want all the files which were selected by user previously.
This code I am using it to store the data in cookies.
if(!angular.isUndefined(filelist)) {
$cookies.filelist = JSON.stringify(filelist).toString();
}
Below code I am using to create filelist object from the files selected by user
$('#fileupload').on('fileuploadadd', function (e, data) {
for(var i = 0; i < data.files.length; i++){
filelist.push(data.files[i])
}
});
Code to retrieve data from cookies
if($cookies.filelist != null && $cookies.filelist != 'undefined' && $cookies.filelist != 'null') {
filelist = $.merge(filelist,JSON.parse($cookies.filelist));
}
When i am storing this filelist object it is of "File" type and when I am retrieve it is of "Object". How can I type cast my object to file object? Is it a correct approach I am following?

You would be better off setting up a file structure on your server for storing the files, then use a database to store the URL of the files, when adding the url to the database you can also add the url to your cookies or in session variables, so when you come back to the page you have all your url's that point to the files. I don't understand why you need the actual file object itself. This is only used by <input file /> to upload to disk.

Related

Passing A Js File Objects Array To Flask

I wonder if someone can help me with this as I'm new to JavaScript.
I have a form, and within it I have a file input. However, when a file is uploaded I need to manipulate it and add new properties. So I extract the file from the input like so:
let uploadedFile = [];
for (let val of this.files) {
uploadedFile.push(val)
}
for (val of uploadedFile){
//Check file extension to classify the file type:
let extension = val.name.split('.')
extension = String((extension[extension.length-1]).toLowerCase());
let fileType = val.type;
//Arrays to hold extensions types we want to identify
const imageExtensions = ['jpeg','jpg','png']
const documentExtensions = ['xls','xlsx','csv','pdf']
//Classify files and push to global files array
if (imageExtensions.includes(extension)){
let newFile = new File([val], `${crname}-nr-${FileCount}.${extension}`, {type: `${fileType}`});
newFile.originalName = `${val.name}`
globalFilesArray.push(newFile);
}
}
So as you can see the new file objects are pushed to an array named 'globalFilesArray'
Now in Flask i'm typically accessing the form data using the request module.
Must I now pass the array into a separate hidden file input so I can access it when the entire form is submitted?
I'm a bit stumped with this because I need this to happen only when the form is submitted so I can also access the rest of the input fields in the form.

Saving Javascript FormData() Object on client side

I have a html page which contains a form element with some text and file input elements.
This from is submitted with an ajax call to the server using a method suggested here: How can I upload files asynchronously?
As you may see in the referenced page from the above link, the FormData() object is used as a container for inputed data and I have done the job successfully.
But now we want to create a new page that have these html elements, save the text and file inputs on client side (Cookie or Local Strorage or . . .) and do the ajax submit later on another page.
I wasn`t able to save new FormData() in either cookie or local storage; what got saved is a small string:"[object FormData]" instead of entered file and strings.
I also tried using JSON.stringify() with no success; it just returned an empty JSON("{}").
(the code is using jQuery selector)
var postData = new FormData($(form)[0]);
// var sPostedData = JSON.stringify(postData); // returns: "{}"
var myStorage = window.localStorage; // returns: "[object FormData]"
myStorage.setItem("contentOrder", postData);
Please help, how should I save this object on my client-side?
To get the file from form data use formData.get('file') where file is the name of an input. The returned object will be of type Blob (see how to get its content).
The complete example can be found in this fiddle: https://jsfiddle.net/skm5m467/1/

How to set the value received from the response to .js or json file

I am using the karate api framework to automate web services.
Currently, I am facing problem to set the response value back to the .js or JSON file which I receive from the cucumber feature file.
My response:{"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001'}
How can I save this to .js or JSON file to reuse them in other scripts [feature files] ?
Thanks in advance.
You cannot save the value to a .js or JSON file provided you don't want to write the value to a json file
You can assign the value to a variable , let say using a namespacing technique to avoid collision
var nameSpaceObject = {
authKey : "",
someOtherFunctionIfNecessary :function(){}
};
Then you can call this name space & assign value to it
var response = {"authorizationtoken" : "58102a8c9e074d578edae8f3d5e96001' }
nameSpaceObject.authKey = response.authorizationtoken;

Meteor-package: Import JSON-array to mongoDB

I'm trying to create a meteor-package to import JSON-files to collections in a mongoDB. But I'm not quite sure, if this is possible.
So I want the user to upload a JSON-file. In a input-field the user also types the collection-name which has to be used for the import. After this the JSON-array should be saved to the given collection.
HTML:
<template name="importJSON">
<form id="importJson">
<input type="text" id="collection">
<input type="file" id="file">
</form>
</template>
meteor:
Template.importJSON.events({
'submit #importJson': function(e){
e.preventDefault();
var collection = e.target.collection.value;
var obj = JSON.parse(response);
db.collection.insert(obj);
}
});
So I have three problems with that:
1) How do I have to do the upload itself, as the file should be uploaded temporarily
2) How can I use the collection name given in the input-field?
3) How do I import the data in a correct way? Insert would just append the new data to the existing data, wouldn't it?
So to answer your three problems:
1) How do I have to do the upload itself, as the file should be uploaded temporarily
If all you need to do is read the file, then insert it into a collection. In that case you do not need to even upload the file. Just read the file in client side. Here is an article on Reading files in JavaScript using the File APIs.
2) How can I use the collection name given in the input-field?
Say the collection name given in the input-field is products and assume you have a sample data file like this:
{
"name": "Product",
"id": "Product identifier",
"name": "Name of the product",
"price": "9990",
"tags": ["tag1", "tag2"]
}
At this point you need to decide how you do this. If you already have a Products collection on server side.
<your app name>/lib/collections/products.js
Products = new Meteor.Collection('Products');
Then in your client side code:
var rawproducts = (content of the file you read using the File API -- as mentioned above)
var newproducts = JSON.parse(rawproducts);
for (var i = 0; i < newproducts.length; i++) {
Products.insert(newproducts[i]);
}
You can also test this out locally by creating a local only collection.
//pass null as collection name, it will create
//local only collection
Products = new Mongo.Collection(null);
for (var i = 0; i < newproducts.length; i++) {
Products.insert(newproducts[i]);
}
Note: If you use a local only collection your data is still on the client. You'll need to sync that with the server (as described above) for persistence.
3) How do I import the data in a correct way? Insert would just append the new data to the existing data, wouldn't it?
Importing the data as shown above will keep on appending the data. You may want to think about how to de-dupe the data or completely overwrite the existing data.
Hope this helps.
Update:
How to delete all the elements from a collection?
Products.remove({}) // remove every product

Performance of edits to localStorage with JavaScript?

According to the W3 Web Storage specs, values in localStorage are of type string.
Thus, an entry can't be granularly updated like a subproperty of a JS object and it's only possible to replace the entire key:
Updating/editing localStorage - JSONObject
Assume I want to "secure" user input frequently on the client side in the localStorage, and also update it on model changes on the server (only transmitting changes from server to client). How often can I JSON.stringify() my local data (=ViewModel state) and save it to the localStorage without causing trouble for the user? Is serializing and saving (not transmitting!) e.g. 30KB of data every 5 seconds to the localStorage going to cause lags?
Bonus question: Does any major browser vendor plan on storing JS objects directly in localStorage?
This may not be entirely true; there is a method for updating a single key to an object housed in local storage, and the code is below.
var updateLocalStorageKey = function(obj, key, val) {
var localObj = JSON.parse(localStorage[obj] )
localObj[key] = val;
//reset storage
localStorage[obj] = JSON.stringify(localObj)
}
The working jsbin is here: http://jsbin.com/jesapifa/4/edit?html,js,output
Hope this solves your problem!

Categories