Uploading files to parse.com with javascript - javascript

I'm attempting to upload an array of files to parse using javascript with the following code:
html:
<fieldset>
<input type="file" name="fileselect" id="fileselect" multiple></input>
<input id="uploadbutton" type="button" value="Upload"> </input>
</fieldset>
JS:
$('#uploadbutton').click(function () {
var fileUploadControl = $("#fileselect")[0];
if (fileUploadControl.files.length > 0) {
var file = fileUploadControl.files[0];
var name = "style.css";
var parseFile = new Parse.File(name, file);
var filesArray = [parseFile];
}
parseFile.save().then(function() {
// The file has been saved to Parse.
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
var newStore = new Parse.Object("FileStore");
newStore.set("files", filesArray);
newStore.save();
});
I am uploading to a class I have called FileStore with key "files" which is set to an array currently, and I would like to have hold an array of files. Is this the best way to go about uploading multiple files to parse? The code for me isn't working right now. My aim is to have multiple files associated with each object in my class.

Be careful with async code. Currently your code will have a race condition that will most likely fail because you call newStore.save() before parseFile.save() is finished.
Those 3 lines dealing with newStore should be inside the success handler for parseFile.save(), e.g.:
parseFile.save().then(function() {
// The file has been saved to Parse.
var newStore = new Parse.Object("FileStore");
newStore.set("files", filesArray);
newStore.save();
}, function(error) {
// The file either could not be read, or could not be saved to Parse.
});
When you get to saving multiple files you'll need to wait for all of them to finish before moving to the next step. You can chain your promises together to run in Series or in Parallel.
For what you want Parallel would work fine:
var fileSavePromises = [];
// assuming some code that creates each file has stored the Parse.File objects in an
// array called "filesToSave" but not yet called save
_.each(filesToSave, function(file) {
fileSavePromises.push(file.save());
});
Parse.Promise.when(fileSavePromises).then(function() {
// all files have saved now, do other stuff here
var newStore = new Parse.Object("FileStore");
newStore.set("files", filesToSave);
newStore.save();
});

I have managed to solve this with the help of #Timothy code, full code after edit:
var fileUploadControl = $("input[type=file]")[0];
var filesToSave = fileUploadControl.files;
var fileSavePromises = [];
// assuming some code that creates each file has stored the Parse.File objects in an
// array called "filesToSave" but not yet called save
_.each(filesToSave, function(file) {
var parseFile = new Parse.File("photo.jpg", file);
fileSavePromises.push(
parseFile.save().then(function() {
// The file has been saved to Parse.
$.post("/i", {
file: {
"__type": "File",
"url": parseFile.url(),
"name": parseFile.name()
}
});
})
);
});
Parse.Promise.when(fileSavePromises).then(function() {
// all files have saved now, do other stuff here
window.location.href = "/";
});

Related

how to read a static file from url in javascript to create an array

I searched but I don't find, I am coding a simulator and I want to do the calculus using javascript, the simulator takes 2 kind of entries. The first entries are given by user, this part is done. The second part is a lot of coefficient which are stored in csv/tsv file, the file is uploaded on the server. And I am not able to read this file, I found a lot of code on how to convert csv to array and I think that I will be able to do it alone. For now I am doing step by step so I just want to read the csv file to put it inside a table, when I use the code shown it works if I use an < input type="file" > but I am not able to make it works with a static url. Can You help me?
function myprocessFile()
{
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
document.getElementById("toto").innerHTML = blob;
if (theFile)
{
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e)
{
// CREATE TABLE
}
myReader.readAsText(theFile);
}
return false;
}
You could use the fetch API :
fetch('url/to/your/csv/file')
.then(function(response) {
return response.text()
})
.then(function(csv) {
// convert your csv to an array
});

How to get objects from txt file to use in javascript array?

I am very new to coding and javascript; just a few days in. I was wondering if there was a way to import objects from a text file(separated by lines) to use in my array: replyText. Here is what I'm working with:
// Variables
var theButton = document.getElementById("theButton");
var mainText = document.getElementById("mainText");
var replyText = [...,...,...,...,];
var i = 0;
// Functions
function nextText() {
mainText.innerHTML = replyText[i++ % replyText.length];
}
// MAIN SCRIPT
theButton.onclick = function() {
nextText();
};
You can use XMLHttpRequest to get the .txt file just pass the path of it.
var file = new XMLHttpRequest();
file.open("GET", "file:/../file.txt", false);
file.onreadystatechange = function () {
if (file.readyState === 4) {
if (file.status === 200 || file.status == 0) {
var text = file.responseText;
alert(text);
}
}
}
EDIT: you must pass the absolute path file:///C:/your/path/to/file.txt
For client/browser-side file reading:
You cannot easily read a file on the client-side as you are not allowed direct access to the client's file system. However, you can place a input element of file type in your HTML markup via which the client can load a file for your program to process. For example:
<input type="file" id="file" onchange="readFile()" />
Now when the client selects a file for use, the readFile() function will be called which will read and process the file. Here's an example:
function readFile() {
var file = document.getElementById('file').files[0]; // select the input element from the DOM
var fileReader = new FileReader(); // initialize a new File Reader object
fileReader.onload(function() { // call this function when file is loaded
console.log(this.result); // <--- You can access the file data from this variable
// Do necessary processing on the file
});
fileReader.readAsText(file); // Read the file as text
}
For more information on File Reader, check out the docs.
To add on to Paulo's solution, read below for splitting string by line breaks (new line character)
var replyText = text.split("\n"); // "\n" is new line character

How to save uploaded image to IndexedDB Javascript

Am using file upload controller to browse images and the selected images should be previewed in the page as image thumbnails.
<input type="file" id="imageSelector" multiple="multiple" />
var uploadImageCtrl = document.querySelector('#imageSelector');
uploadImageCtrl.addEventListener('change', function () {
var files = this.files;
for(var i=0; i<files.length; i++){
preview(this.files[i]);
}
}, false);
After selecting few images, go to next page and do some action. And when going back from that page, all the image previews should be there. I thought of saving these images to IndexedDB, before going to next page. But am not sure how to code for IndexedDB in this case.
Can anyone help me?
File objects are cloneable and can be saved to Indexed DB, either as records on their own or as part of other records.
This example just saves an array of files as a single record (key is "key") to an object store named "images":
// Call with array of images; callback will be called when done.
function save(array_of_files, callback) {
openDB(function(db) {
var tx = db.transaction('images', 'readwrite');
tx.objectStore('images').put(array_of_files, 'key');
tx.oncomplete = function() { callback(); };
tx.onabort = function() { console.log(tx.error); };
});
}
// Callback will be called with array of images, or undefined
// if not previously saved.
function load(callback) {
openDB(function(db) {
var tx = db.transaction('images', 'readonly');
var req = tx.objectStore('images').get('key');
req.onsuccess = function() {
callback(req.result);
};
});
}
function openDB(callback) {
var open = indexedDB.open('my_db');
open.onupgradeneeded = function() {
var db = open.result;
db.createObjectStore('images');
};
open.onsuccess = function() {
var db = open.result;
callback(db);
};
open.onerror = function() { console.log(open.error); };
}
One possible gotcha: HTMLInputElement's files is not an Array itself but an array-like type called FileList. You can convert it to an array with e.g. Array.from(e.files), but a FileList can be cloned (and therefore stored in IDB) so this should "just work".

Is Parse's Javascript file upload broken?

I've been trying to save a user-uploaded image to parse for the longest time, and nothing seems to work -- even when following their documentation.
Below is the handler I use for the onChange() on a multiple file upload. At first I was concerned about multiple file uploads, but at this point just saving one image doesn't work.
function fileHandler(event) {
var files = event.target.files;
stopPictures = [];
$("#stop-img-container").empty();
if (files[0] != null) {
$("#stop-img-container").show();
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
picReader.addEventListener("load",function(event){
var picFile = event.target;
var image = $("<img/>",{
"title": picFile.name,
"class": "stop-image",
"src": picFile.result
}).appendTo("#stop-img-container");
var name = picFile.name;
var dataFile = picFile.result;
var base64str = dataFile.substring(dataFile.indexOf("base64,")+7,dataFile.length);
var parseFile = new Parse.File(name,{base64:base64str}); // saving logs 404 Not Found from POST to "http://api.parse.com/1/files"
var parseFile = new Parse.File(name,dataFile); // saving logs "Uncaught Creating a Parse.File from a String is not yet supported."
var parseFile = new Parse.File(name,file); // saving logs 404 Not Found from POST to "http://api.parse.com/1/files"
var parseFile = new Parse.File(name,base64str); // saving logs "Uncaught Creating a Parse.File from a String is not yet supported."
parseFile.save().then(function (savedFile) {
stopPictures.push(savedFile);
alert("worked");
});
});
picReader.readAsDataURL(file);
}
} else {
$("#stop-img-container").hide();
}
}
There's some extraneous stuff here, but basically it collects the user's selected files, displays them for them once they've finished loading, and then creates them as a Parse file. I've left it in to show that at least something is working as it properly locally stores and previews the user's selected files.
I have included three different ways of creating the same Parse file. However, all of them fail when I try to save to Parse in any way.
Parse's Javascript API docs says that any of these should work fine. But they lie, or I'm an idiot.
Anyone have any idea why this doesn't seem to work? Seems like a pretty critical aspect of their API is broken completely -- which I find hard to imagine.
EDIT: I'm also positive I'm properly parsing (lower case p) the base64 string as this site confirms the appropriate image and works.
I experienced the same problem.
Finally I found what causes the problem.
It's a "file name".
I suspect the file name in tuckerchapin's example is null.
var name = picFile.name;
I wrote the example with React.
this code works fine.
class ImageUpload extends React.Component {
onChange(e) {
var file = e.target.files[0];
var parseFile = new Parse.File(file.name, file);
Parse.User.current().set("icon",parseFile);
Parse.User.current().save();
}
handleSubmit(e) {
e.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="file" onChange={this.onChange.bind(this)} />
</form>
);
}
}

Load multiple JSON files in pure JavaScript

I am new to JavaScript. I have already understood how to create an object from a JSON-file with JSON.Parse() and now I need to load multiple local JSONs into an array. I've been googling my problem for a while, but everything that I found was related to single JSON files.
Is there any way to do this in pure JavaScript without any libraries like jQuery and etc.?
P.S.: There is no need to work with web-server or else, the code is running locally.
To do this, you need to first get the actual files. Then, you should parse them.
// we need a function to load files
// done is a "callback" function
// so you call it once you're finished and pass whatever you want
// in this case, we're passing the `responseText` of the XML request
var loadFile = function (filePath, done) {
var xhr = new XMLHTTPRequest();
xhr.onload = function () { return done(this.responseText) }
xhr.open("GET", filePath, true);
xhr.send();
}
// paths to all of your files
var myFiles = [ "file1", "file2", "file3" ];
// where you want to store the data
var jsonData = [];
// loop through each file
myFiles.forEach(function (file, i) {
// and call loadFile
// note how a function is passed as the second parameter
// that's the callback function
loadFile(file, function (responseText) {
// we set jsonData[i] to the parse data since the requests
// will not necessarily come in order
// so we can't use JSONdata.push(JSON.parse(responseText));
// if the order doesn't matter, you can use push
jsonData[i] = JSON.parse(responseText);
// or you could choose not to store it in an array.
// whatever you decide to do with it, it is available as
// responseText within this scope (unparsed!)
}
})
If you can't make an XML Request, you can also use a file reader object:
var loadLocalFile = function (filePath, done) {
var fr = new FileReader();
fr.onload = function () { return done(this.result); }
fr.readAsText(filePath);
}
You can do something like this:
var file1 = JSON.parse(file1);
var file2 = JSON.parse(file2);
var file3 = JSON.parse(file3);
var myFileArray = [file1, file2, file3];
// Do other stuff
// ....
// Add another file to the array
var file4 = JSON.parse(file4);
myFileArray.push(file4);
If you already have an array of un-parsed files you could do this:
var myFileArray = [];
for(var i=0; i<unparsedFileArray.length; i++){
myFileArray.push(JON.parse(unparsedFileArray[i]));
}

Categories

Resources