How do I get the file from the form to save it to Parse?
I tried several dozen variations of this:
<form id="image_form" enctype="multipart/form-data" action="/upload/image" method="post">
<h3>Upload icon image: </h3>
<p><input id="image_file" name="image_file" type="file"></p>
<p><input id="event_submit" type="submit" value="Create" onclick="makeEventSnip();"></p>
</form>
and in the javascript:
function makeEventSnip() {
event.preventDefault();
var fileUploadControl = document.getElementById('image_file');
var file = fileUploadControl.files[0];
var name = "icon.png";
var iconImageFile = new Parse.File(name, file);
alert(iconImageFile.getUrl());
I tried to do it the way they say to in Parse's JS Guide (https://parse.com/docs/js/guide) but that doesn't work either. It doesn't appear to be grabbing anything from the form. What am I missing?
try this
var fileUploadControl = document.getElementById('image_file');
var file = fileUploadControl.files[0];
var name = "icon.png";
var iconImageFile = new Parse.File(name, file);
iconImageFile.save().then(function() {//you need to call after save the file
alert(iconImageFile._url);
}
Related
I've created a custom Google Form which allows a logged in Google user to include multiple files with the form.
The files are uploaded into a newly created folder in Google Drive.
The Google Script uses the current user's email address + current date and time as the folder name.
Problem and expected result:
Because of the forEach function, the script uploads each file into a separate folder (with the same name).
I would like to upload each file of one form submission into one folder.
HTML:
<iframe name="hidden_iframe" id="hidden_iframe" style="display:none;" onload="if(submitted) { picUploadJs(myForm); }"></iframe>
<form id="myForm" class="col s12" action="https://docs.google.com/forms/d/e/xxx/formResponse" target="hidden_iframe" onsubmit="submitted=true;">
<input placeholder="1234" name="entry.1234" id="user" type="text">
<label for="user">User:</label>
<input name="picToLoad" type="file" id="sampleFile" />
<div id="status" style="display: none">
Uploading. Please wait...
</div>
<button type="submit" name="action">Send</button> <!-- Modified -->
</form>
Javascript:
function picUploadJs(myForm) {
const f = document.getElementById("files");
[...f.files].forEach((file, i) => {
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
const obj = {fileName: file.name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]};
document.getElementById('status').style.display = 'inline';
google.script.run.withSuccessHandler(updateOutput).processForm(obj);
}
fr.readAsDataURL(file);
});
}
function updateOutput() {
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = "The File was UPLOADED!";
window.location='https://Thankyou';
}
Google Script:
function doGet(e) {
Logger.log("doGet done");
return HtmlService.createTemplateFromFile('test')
.evaluate() // evaluate MUST come before setting the Sandbox mode
.setTitle('Form')
//.setSandboxMode();//Defaults to IFRAME which is now the only mode available
}
function processForm(theForm) {
var dateTime = Utilities.formatDate(new Date(), "GMT+2", "dd-MM-yy_HH-mm");
var email = Session.getActiveUser().getEmail();
var parentFolder=DriveApp.getFolderById('xxxxx');
var newFolder=parentFolder.createFolder(email + "_" + dateTime);
var newFolderId = DriveApp.getFoldersByName(newFolder).next().getId();
var fileBlob = Utilities.newBlob(Utilities.base64Decode(theForm.data), theForm.mimeType, theForm.fileName);
var fldrSssn = DriveApp.getFolderById(newFolderId);
fldrSssn.createFile(fileBlob);
return true;
}
When the files are submitted, you want to create one new folder every submitting.
You want to upload multiple files to the created folder.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
Modified scripts:
HTML:
Please modify as follows.
From:
<input name="picToLoad" type="file" id="sampleFile" />
To:
<input name="picToLoad" type="file" id="files" multiple />
Javascript:
Please modify picUploadJs().
function picUploadJs(myForm) {
const f = document.getElementById("files");
google.script.run.withSuccessHandler((folderId) => { // Added
var files = [...f.files];
files.forEach((file, i) => {
const fr = new FileReader();
fr.onload = (e) => {
const data = e.target.result.split(",");
const obj = {fileName: file.name, mimeType: data[0].match(/:(\w.+);/)[1], data: data[1]};
document.getElementById('status').style.display = 'inline';
google.script.run.withSuccessHandler(() => {
if (i == files.length - 1) updateOutput();
}).processForm(obj, folderId); // Modified
}
fr.readAsDataURL(file);
});
}).createFolder();
}
Google Apps Script:
I separated processForm() to processForm() and createFolder().
// Added
function createFolder() {
var dateTime = Utilities.formatDate(new Date(), "GMT+2", "dd-MM-yy_HH-mm");
var email = Session.getActiveUser().getEmail();
var parentFolder = DriveApp.getFolderById('xxxxx');
var newFolder = parentFolder.createFolder(email + "_" + dateTime);
var newFolderId = DriveApp.getFoldersByName(newFolder).next().getId();
return newFolderId;
}
// Modified
function processForm(theForm, newFolderId) {
var fileBlob = Utilities.newBlob(Utilities.base64Decode(theForm.data), theForm.mimeType, theForm.fileName);
var fldrSssn = DriveApp.getFolderById(newFolderId);
fldrSssn.createFile(fileBlob);
return true;
}
Note:
In your HTML, the top line is as follows.
<form id="myForm" target="hidden_iframe" onsubmit="submitted=true;">
From your previous question, if you are using the following lines, please update your question. I supposed that you are using the following script.
<iframe name="hidden_iframe" id="hidden_iframe" style="display:none;" onload="if(submitted) { picUploadJs(myForm); }"></iframe>
<form id="myForm" action="https://docs.google.com/forms/d/e/xxx/formResponse" target="hidden_iframe" onsubmit="submitted=true;">
If this was not the result you want, I apologize.
I'm completely new to the subject of JSON and I was wondering how to parse JSON from an input value in my form.
I'm trying to string the inputs into an array like {"task" : "(input) ", "(input) "} {"description" : "(input ", "(input)"}
I tried to follow the same directions as this post: Adding a new array element to a JSON object but they're referring to strings already formulated when I want to be able to parse JSON the same way from an input in my form. I want to be able to save every input and add a new array element the same way.
Bottom code runs smoothly but I'm such a noobie at parsing JSON D: any help is appreciated.
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
myJSON = JSON.stringify(FormData);
localStorage.setItem("formJSON", myJSON);
text = localStorage.getItem("formJSON");
obj = JSON.parse(text);
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};
newArray = [task, description];
var taskArray = [];
var descriptionArray = [];
var task = document.getElementById("task").value;
var description = document.getElementById("description").value;
function addTask(task) {
taskArray.push(task);
console.log(
"Tasks: " + taskArray.join(", "));
}
function addDescription(description) {
descriptionArray.push(description);
console.log("Description: " + descriptionArray.join(", "));
};
<!DOCTYPE html>
<html>
<title>Task Form</title>
<body>
<form class="form-inline" name="myForm" onsubmit=" return submitForm()">
<label class="required">*Task and Description* </label>
<!first text box>
<div class="form-group">
<input type="text" id="task" placeholder="Task">
</div>
<!second comment box>
<div class="form-group">
<input type="text" id="description" placeholder="Description">
</div>
<button type="submit" class="btn btn-default submit">Submit</button>
</form>
<script type="text/javascript " src="json.js "></script>
</body>
</html>
You should be storing the array of all tasks in localStorage, not just a single task. When the user saves a new task, read the JSON from local storage, parse it, add the new task to the array, and save that.
function submitForm() {
var task = myForm.task.value;
var desc = myForm.description.value;
var FormData = {
task: task,
description: desc
};
var arrayJSON = localStorage.getItem("formJSON") || "[]";
var taskArray = JSON.parse(arrayJSON);
taskArray.push(FormData);
localStorage.setItem("formJSON", JSON.stringify(taskArray));
addTask(task);
addDescription(desc);
console.log(FormData);
return false;
};
Here i am converting two images for base64 ,this one working fine after that i want make one json format, so i am trying like this but i no able to get answer. i am getting error like "message": "Uncaught ReferenceError: floor_image is not defined", how to solve this issue and send json format
$(document).ready(function(){
$('#submit').click(function(){
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var floor_image = fileLoadedEvent.target.result; // <--- data: base64
console.log("Converted Base64 version 1 " + floor_image); // i am getting answer here
}
fileReader.readAsDataURL(fileToLoad);
}
var filesSelected = document.getElementById("inputFileToLoad1").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
var property_image = fileLoadedEvent.target.result; // <--- data: base64
//console.log("Converted Base64 version 2 " + property_image); // i am getting answer here
}
fileReader.readAsDataURL(fileToLoad);
}
var json = {
"FloorImage" :floor_image,
"PropertyImage" : property_image
}
console.log(json);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form id="idname">
<input id="inputFileToLoad" type="file" /><br><br>
<input id="inputFileToLoad1" type="file" />
<br><br><br><br>
<input type="button" value="Submit" id="submit">
</form>
You do not have the floor_image in the global scope. Try to write var floor_image; outside of the method, then set floor_image to your result as you do, but remove the var keyword in the method. The same goes for property_image and json
Like this:
$(document).ready(function(){
var json={FloorImage:"not loaded yet",PropertyImage:"not loaded yet"};
var floor_image;
var property_image;
$('#submit').click(function(){
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
floor_image = fileLoadedEvent.target.result;
json.FloorImage=floor_image;
}
fileReader.readAsDataURL(fileToLoad);
}
var filesSelected = document.getElementById("inputFileToLoad1").files;
if (filesSelected.length > 0) {
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent) {
property_image = fileLoadedEvent.target.result;
json.PropertyImage=property_image;
}
fileReader.readAsDataURL(fileToLoad);
}
console.log(json); // you are logging the json before the images are loaded, because this code is executed before the code inside onLoad.
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="idname">
<input id="inputFileToLoad" type="file" /><br><br>
<input id="inputFileToLoad1" type="file" />
<br><br><br><br>
<input type="button" value="Submit" id="submit">
</form>
Scenario
Try to load the FloorImage first, you will see the text: "not loaded yet" in both properties of the json-object. Then try to load the PropertyImage, and you will se the base64 of the FloorImage inside your json-object, but the text "not loaded yet" on the PropertyImage. This is because the images are not finished loading when you print the json-object. However the images are there after the onload-method is done.
There are 2 problems:
floor_image and property_image are in local scope. You should
move them to click function's scope
onload is just a callback. It means that json object may
be created before files have loaded. You should only create it after
2 onload functions called (for example, use flag to determine
onload called or not, and only create json when both of them are
true)
i have the following code, the issue i have is that i am getting a error of e.originalEvent.dataTransfer is undefined.
my code is as follows
HTML
Select images: <input type="file" id='fileupload' name="userfile[]" multiple>
Javascript is as follows
var hot = $('#fileupload');
hot.change(function (e)
{
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
//send dropped files to Server
handleFileUpload(files,hot);
});
function handleFileUpload(files,obj)
{
for (var i = 0; i < files.length; i++)
{
var fd = new FormData();
var e = document.getElementById("child_id");
fd.append('userfile[]', files[i]);
var filename=files[i].name;
var status = new createStatusbar(obj,files[i]); //Using this we can set progress.
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status,filename);
}
}
The attribute files belongs to the input field. This you'll get by the target attribute.
If I test the setting above, I have success with this descriptor:
e.originalEvent.target.files
Then, files is an array of File objects, containing name, lastModifiedDate, type etc.
We are working on a Email Encrypted Service. Here I have designed a html page (User Registration) where I have provided an area for uploading a file with extentions .crt, .cer and .der
This is HTML Content:
<section>
<label class="label">PubLic Key File</label>
<div>
<input type="file" id="fileInput">
</div>
<div id="fileDisplayArea"></div>
</section>
<button type="submit" class="button">Submit</button>
Javascript Code is:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!";
}
});
}
I have copied this Javascript Code (beginner in javascript) . It Only Accepts image file. I want to change this code which only accepts .crt, .cer and .der Extentions.
Thank you :)
Your current regex will actually match any filename that contains the word "image" (any part of the filename that is "image" followed by zero or more characters)
If you want to match filenames that end in ".crt", ".cer" or ".der", you can use this regex:
var imageType = /\.crt|cer|der$/
You can test regular expressions using Rubular