first of all I want to say I know almost nothing about javascript. I'm trying to develop a form with google app script where you can upload a file and it will automatically put it in a specific folder based on the response you enter in the form. For example, if I'm asking in the form which class you want to choose, and the user choose class "1", then the file will be uploaded in the "class 1" folder. With the help of the answers in this forum, I was able to create something that should work, but for some reason it is not. With my limited knowledge I'm not able to find the issue, even if this is a very easy fix, because as I said I don't know well Javascript. Some of the words in the code are in Italian, hope this is not a problem. This is my code, but for some reasons it is not working:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
if(form.classi == "classe1") {
var dropbox = "Classi prime";
}
else if(form.classi == "classe2") {
var dropbox = "Classi seconde";
}
else if(form.classi == "classe3") {
var dropbox = "Classi terze";
}
else if(form.classi == "classe4") {
var dropbox = "Classi quarte";
}
else if(form.classi == "classe5") {
var dropbox = "Classi quinte";
}
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var fileBlob = form.myFile;
var fname = fileBlob.getName();
var newName = form.myLastName+form.myFirstName; // simple example
// extract extension using RegEx
// from http://stackoverflow.com/a/680982/1677912
var extensionfinder = /(?:\.([^.]+))?$/;
var ext = extensionfinder(fname)[1];
fileBlob.setName(newName+'.'+ext);
var file = folder.createFile(blob);
file.setDescription("Caricato da " + form.myFirstName+form.myLastName);
return "<p> Il tuo file è stato caricato correttamente, " + form.myFirstName + "!";
}
catch (error) {
return error.toString();
}
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<title>Caricamento file Liceo Augusto</title>
<style>
input[type=text], select, textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
margin-top: 6px;
margin-bottom: 16px;
resize: vertical
}
input[type=submit] {
background-color: #c72222;
color: white;
padding: 12px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #6e1010;
}
.container {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
margin: auto;
width: 70%;
border: 3px solid black;
}
</style>
</head>
<body>
<h1><center>Compila il modulo per inviare il tuo documento</center></h1>
<div class="container">
<form id="uploadFilesForm">
<label for="classe">Seleziona la classe:</label>
<select id="classi" name="classi">
<option value="classe1">1</option>
<option value="classe2">2</option>
<option value="classe3">3</option>
<option value="classe4">4</option>
<option value="classe5">5</option>
</select>
<label for="name">Nome:</label>
<input type="text" id="fname" name="myFirstName" placeholder="Il tuo nome...">
<label for="lname">Cognome:</label>
<input type="text" id="lname" name="myLastName" placeholder="Il tuo cognome...">
<input type="file" name="myFile">
<br><br>
<center><input type="submit" value="Invia documento"
onclick="this.value='Caricamento...';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;"
>
</center>
</form>
</div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
</body>
</html>
Related
I am working on a bookmark "collector" app that allows users save websites urls as a collection. I have created an array collectX in the localstorage to save each collections. However I am trying to edit and update each collections that have created on another HTML page.
How can I do that?
Here is what I have tried so far:
//get form values
// create an object of the form values
//create an empty array
//append object of the form values to the empty array
//display array object values
showCollection();
var getButton = document.getElementById('clickIt');
var collectionTitle = document.getElementById("title");
var collectionDescription = document.getElementById('describe')
getButton.addEventListener('click', function(e){
e.preventDefault()
var collections = {
title: collectionTitle.value,
description: collectionDescription.value,
collectedWebsites:[]
}
let webCollections = localStorage.getItem('collectx');
if(webCollections == null){
var collectionObj = []
alert('storage is empty')
}
else{
collectionObj = JSON.parse(webCollections);
}
collectionObj.push(collections);
localStorage.setItem("collectx", JSON.stringify(collectionObj));
showCollection()
});
function showCollection(){
let webCollections = localStorage.getItem('collectx')
if(webCollections == null){
var collectionObj = []
alert('storage is empty')
}
else{
collectionObj = JSON.parse(webCollections);
}
let html= ''
var demos = document.getElementById('demo');
collectionObj.forEach(function(item, index){
html += `<div class="collects">
Title: ${item.title} <br>
Description: ${item.description} </div>`
})
demos.innerHTML = html
}
body{
background-color: #000;
}
.collects{
width: 150px;
height: 100px;
padding: 10px 5px 10px 5px;
margin-right: 20px;
border-radius: 10px;
display: inline-block;
background-color: #fff;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CollectX</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<form id="forms">
<input id="title" type="text" placeholder="Collection name">
<br>
<br>
<input id="describe" type="text" placeholder="Description">
<button id="clickIt"> Submit </button>
</form>
<div id="demo">
</div>
<script src="/script.js"></script>
</body>
</html>
Here is the link to the JSFiddle: https://jsfiddle.net/c3jgezwr/2/
P.S: I have tried to the method used on this page: https://www.xul.fr/javascript/parameters.php
Please take a look to this example
CSS
body {
background-color: #000;
}
.collects {
min-width: 150px;
min-height: 100px;
padding: 10px 5px 10px 5px;
margin-right: 20px;
border-radius: 10px;
display: inline-block;
background-color: #fff;
overflow: hidden;
}
HTML
<form name="form">
<div>
<input name="title" placeholder="Title" />
</div>
<div>
<input name="describe" placeholder="Describe" />
</div>
<div>
<input name="links" placeholder="Add links separated by coma" />
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
JS
const form = document.forms.form;
form.addEventListener("submit", submitHandler);
function getData() {
return JSON.parse(localStorage.getItem("collectx")) ?? [];
}
function submitHandler(event) {
event.preventDefault();
const form = event.target;
const formData = new FormData(event.target);
const data = Object.fromEntries(formData);
const currentData = getData();
localStorage.setItem("collectx", JSON.stringify([...currentData, data]));
form.reset();
render();
}
function render() {
const collection = getData();
const entries = collection
.map(
({ title, describe, links }) => `
<div class="collects">
<p>Title: ${title}</p>
<p>Describe: ${describe}</p>
<p>Links: ${links && links
.split(",")
.map((link) => `${link}`)
.join("<br />")}
</p>
</div>`
)
.join("");
document.querySelector("#root").innerHTML = `
<div>
${entries}
</div>
`;
}
render();
https://jsfiddle.net/m3ws94zo/2/
The idea is to add a input to enter links separated by coma. In a real solution, you probably will need to validate the urls
I have a program for a makeshift task list that I am working on that should allow a user to enter more than one task by separating the tasks with a comma. I am not sure how I would write a portion of code to allow this function. I am trying to also make the lists themselves separate so if a user needed to delete a task, all the tasks would not be deleted too.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var tasks = [];
var displayTaskList = function() {
var list = "";
// if there are no tasks in tasks array, check storage
if (tasks.length === 0) {
// get tasks from storage or empty string if nothing in storage
var storage = localStorage.getItem("tasks") || "";
// if not empty, convert to array and store in global tasks variable
if (storage.length > 0) { tasks = storage.split("|"); }
}
// if there are tasks in array, sort and create tasks string
if (tasks.length > 0) {
tasks.sort();
list = tasks.join("\n");
}
// display tasks string and set focus on task text box
$("task_list").value = list;
$("task").focus();
};
var addToTaskList = function() {
var task = $("task");
if (task.value === "") {
alert("Please enter a task.");
} else {
// add task to array and local storage
tasks.push(task.value);
localStorage.tasks = tasks.join("|");
// clear task text box and re-display tasks
task.value = "";
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("task_list").value = "";
$("task").focus();
};
window.onload = function() {
$("add_task").onclick = addToTaskList;
$("clear_tasks").onclick = clearTaskList;
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 700px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<!DOCTYPE html>
<html>
<head>
<title>Ch09 Task Manager</title>
<link type="text/css" rel="stylesheet" href="task_list.css">
<script type="text/javascript" src="task_list.js"></script>
</head>
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
</body>
</html>
I found a lot of other stuff that needed fixing, so I did (mostly having to do with how you use jQuery). Works for me locally. Snippet runner doesn't want to do some of this stuff - sorry! Don't know about that.
var tasks = [];
var displayTaskList = function() {
var list = "";
if (tasks.length === 0) { // if there are no tasks in tasks array, check storage
var storage = localStorage.getItem("tasks") || ""; // get tasks from storage or empty string if nothing in storage
if (storage.length > 0) {
tasks = storage.split("|");
} // if not empty, convert to array and store in global tasks variable
}
if (tasks.length > 0) { // if there are tasks in array, sort and create tasks string
tasks.sort();
list = tasks.join("\n");
}
$("#task_list").val(list); // display tasks string and set focus on task text box
$("#task").focus();
};
var addToTaskList = function() {
var task = $("#task").val();
console.log(`entering addtotask list with task value = ${task}`);
if (task === "") {
alert("Please enter a task.");
} else {
if (task.indexOf(',') === -1) {
tasks.push(task); // add task to array and local storage
} else {
const split = task.split(','); // 2 lines for readability
split.forEach(atask => {
tasks.push(atask);
});
}
localStorage.tasks = tasks.join("|");
$("#task").val(""); // clear task text box and re-display tasks
displayTaskList();
}
};
var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("#task_list").val("");
$("#task").focus();
};
window.onload = function() {
$("#add_task").on('click', function() {
addToTaskList();
});
$("#clear_tasks").on('click', function() {
clearTaskList();
});
displayTaskList();
};
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size: 100%;
background-color: white;
width: 800px;
margin: 0 auto;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
font-size: 150%;
color: blue;
margin-bottom: .5em;
}
label {
float: left;
width: 8em;
}
input {
width: 22em;
margin-right: 1em;
margin-bottom: 1em;
}
#tasks {
margin-top: 0;
float: right;
}
<body>
<main>
<h1>Task Manager</h1>
<div id="tasks">
<span id="name"> </span>Tasks<br>
<textarea id="task_list" rows="8" cols="50"></textarea>
</div>
<label for="task">Task</label><br>
<input type="text" name="task" id="task"><br>
<input type="button" name="add_task" id="add_task" value="Add Task">
<input type="button" name="clear_tasks" id="clear_tasks" value="Clear Tasks"><br>
<input type="button" name="delete_task" id="delete_task" value="Delete Task">
<input type="button" name="toggle_sort" id="toggle_sort" value="Toggle Sort"><br>
<input type="button" name="set_name" id="set_name" value="Set Name">
<input type="button" name="filter_tasks" id="filter_tasks" value="Filter Tasks"><br>
</main>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>
</body>
Please help - I am getting Cannot Get / in my NodeJS application. Why do I get this message?
I know it was here, sorry, but I can't figure out why I get the message.
I tried everything that I could and I still don't get it.
.............
.............
.............
.............
.............
index.js
var express=require('express');
var filePersonData = require("fs")
var jsonData=require('./persons.json');
var parser = require("body-parser");
var jsonFile = "./persons.json"
var app=express();
app.use(parser.urlencoded({extended:true}));
app.use(parser.json());
app.use(express.static("./web"));
// WRITE TO FILE
function readPerson(){
var file = filePersonData.readFileSync(jsonFile, "utf-8");
var jsonDATA = JSON.parse(file);
return jsonDATA;
}
// WRITE NEW PERSON TO FILE
function addPerson(person){
var jsonDATA = readPerson();
jsonDATA.persons.push(person);
filePersonData.writeFileSync(jsonFile, JSON.stringify(jsonDATA));
}
// CHECK IF PERSON EXIST
function ifExist(newPerson){
var jsonDATA = readPerson();
for(var person of jsonDATA.persons){
if(person.name.toLowerCase() == newPerson.name.toLowerCase())
return true;
}
return false;
}
// post to web
app.post("/api/newPerson", function(request, response) {
var person =request.body;
if(ifExist(person)){
response.status(400);
}else{
response.status(201);
addPerson(person);
}
response.send();
});
app.get('/api/persons',(req,res)=>{
res.status(200);
var jsonDATA = readPerson();
res.send(JSON.stringify(jsonDATA));
});
// listening to port 3500
app.listen(3500,
()=>{console.log("Server is listening to port 3500")});
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
input[type=text],
select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.center {
margin: auto;
width: 60%;
border: 3px solid #73AD21;
padding: 10px;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
</style>
<script>
function loadData() {
let optionList = document.getElementById('country').options;
let options = ["Afghanistan", "Åland Islands", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua
and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria",
"Azerbaijan", "Bahamas", "Bahrain"];
options.forEach(option =>
optionList.add(new Option(option, option)));
}
//Get the person info
function newPerson() {
var person = {
name: document.getElementById("name").value,
age: Number(document.getElementById("age").value),
isMale: Boolean(document.getElementById("isMale").checked),
country: document.getElementById("country").value
};
//Check validation
if (!validateParameters(person)) {
return;
}
//fetch : get the web
fetch(`/api/newPerson`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(person),
})
.then(res => {
if (res.status == 201) {
alert(person.name + " added successfully");
window.location = "/personsData.html";
} else if (res.status == 400) {
alert("ERROR: Name already exist");
}
})
.catch(err => console.log(`ERROR : ${err}`));
}
/*
* Validation : person input
* Check if person name between 3-15
* Check if person age betwen 0-120
*/
function validateParameters(person) {
if (person.name.length < 3 || person.name.length > 15) {
alert("The name : " + person.name + " must contain more that 3
latters and below 15 ");
return false;
}
if (person.age < 0 || person.age > 120 || person.age == "") {
alert("The age " + person.age + " is wrong neew to be between 1-
120");
return false;
}
return true;
}
</script>
</head>
<body onload="loadData()">
<div class="center">
<label style="font-size:30px;">Name:</label>
<input style="font-size:20px;" type="text" id="name" placeholder="Your
name..." />
</div>
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Age:</label>
<input style="font-size:20px;" type="number" id="age" placeholder="Your
age..." />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Is Male ? </label>
<input style="font-size:20px;" type="checkbox" id="isMale" />
</div>
<br/>
<div class="center">
<label style="font-size:30px;">Country:</label>
<select style="font-size:20px;" id="country" placeholder="Your
country...">
</div>
<div class="center">
</select>
<br/>
<br/>
<input onclick="newPerson()" type="submit" value="ADD"></input>
</div>
</body>
</html>
personsData.html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
div {
height: 1500px;
width: 80%;
background-color: powderblue;
}
b.filds {
font-size: 30px;
color: rgb(99, 31, 189);
padding-right: 10px;
padding-left: 10px;
}
body {
color: rebeccapurple;
}
h1 {
text-decoration: underline;
}
</style>
<script>
//Add all persons to personView string and print the data to html page
function formatPersons(personList) {
var personView = "";
for (person of personList) {
personView += `<b class="filds">| Name:</b>
<b class="filds">${person.name}</b>,</b>
<b class="filds">| Age: </b>
<b class="filds"><b class="filds">${person.age}</b>,</b>
<b class="filds">| is Male: </b>
<b class="filds"><b class="filds">${person.isMale}</b>,</b>
<b class="filds">| Country: </b>
<b class="filds"><b class="filds">${person.country}</b>.</b>
<br\>`;
}
document.getElementById("body").innerHTML = personView;
}
//Load data from persons JSON
function getAllPersons() {
fetch(`/api/persons`)
.then(res => res.json())
.then(body => formatPersons(body.persons))
.catch(err => console.log(`Error: ${err}`));
}
</script>
</style>
</head>
<body onload="getAllPersons()">
<h1>Persons data</h1>
<div>
<p id="body"></p>
</div>
</body>
</html>
When you hit the express server, it searches for index.html for path "/" by default. In your case, you don't have both defined. you should be able to access both of your pages with localhost:port/form.html" and localhost:port/personsData.html.
I have this form which has a button for file upload. When you select a file it shows at upload_prev div.
My problem is that when I try to select the same file nothing happens. I would like a validation or kind of non duplication function to run.
I did that. I tried many things and methods like using child nodes and seeing if the inner text is the same. I tried to loop using jquery each and getting the value, but all of them failed. I want to display a message that this file is already in the Box of upload_prev when I select it again.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.1.js"></script>
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<style type="text/css">
.fileUpload {
position: relative;
overflow: hidden;
margin: 10px;
}
.fileUpload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
background-color: #fff;
filter: alpha(opacity=0);
}
.buttonwrap {
text-align: center;
padding-top: 20px;
float: left;
display: block;
}
.buttonsend:hover {
background-color: rgba(255, 255, 255, 0.2);
color: #225C51;
}
.buttonsend {
text-decoration: none;
color: #fff;
font-size: 18px;
padding-top: 5px;
padding-bottom: 5px;
padding-left: 10px;
padding-right: 10px;
background-color: rgba(72, 133, 130, .5);
}
span {
float: left;
display: flex;
width: 100%;
}
p.closed {
margin: 0 0 0 7px;
cursor: pointer;
}
</style>
<title></title>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
// TO CLOSE THE SLECTED FILE
$(document).on('click', '.close', function() {
$(this).parents('span').remove();
})
//JUST TO PUT A VALUE IN THE BOX WHICH HAS
document.getElementById("uploadBtn").onchange = function() {
document.getElementById("uploadFile").value = this.value;
};
document.getElementById('uploadBtn').onchange = uploadOnChange;
//document.getElementById('uploadBtn').onchange = myFunction;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
// alert (filename);
var files = $('#uploadBtn')[0].files;
for (var i = 0; i < files.length; i++) {
$("#upload_prev").append('<span>' + '<div class="hesh">' + files[i].name +'</div>' + '<p class="close">X</p></span>');
}
document.getElementById('filename').value = filename;
document.getElementById("demo").innerHTML = files.length;
}
});//]]>
</script>
</head>
<body>
<FORM METHOD="post" ACTION="" ENCTYPE="multipart/form-data">
<!-- <input id="uploadFile" placeholder="Add files from My Computer" class="steptextboxq3" />-->
<div class="fileUpload btn btn-primary">
<span>Browse</span>
<input id="uploadBtn" type="file" class="upload" multiple="multiple" name="browsefile" />
</div>
<input id="filename" type="text" />
<div id="upload_prev"></div>
<div style="clear:both;"></div>
<div class="buttonwrap">
Send </div>
</FORM>
<p id="demo"></p>
</body>
</html>
This is my fiddle. How can I find a way to do this.
https://jsfiddle.net/Lc5gb7c9/
You can create an array to store files[i].name, use Array.prototype.indexOf() to check if file name has been added to array, if true call alert(), else add file name to array. You can reset array to [] at any point during process.
Note, <div> and <p> elements are not valid content of <span> element
// outside of `onchange`
var arr = [];
for (var i = 0; i < files.length; i++) {
if (arr.indexOf(files[i].name) === -1) {
arr.push(files[i].name)
$("#upload_prev").append('<div>'
+ '<div class="hesh">'
+ files[i].name + '</div>'
+ '<p class="close">X</p></div>');
} else {
alert(files[i].name + " already selected")
}
}
jsfiddle https://jsfiddle.net/Lc5gb7c9/2/
There is a low chance that a file with same name, size, type, modified time to repeat and have different content
const existingFiles = []
function findFile(file) {
return existingFiles.find(function(existingFile) {
return (
existingFile.name === file.name &&
existingFile.lastModified === file.lastModified &&
existingFile.size === file.size &&
existingFile.type === file.type
)
})
}
const input = document.querySelector('input')
input.addEventListener('change', function(e) {
const files = e.target.files
Array.from(files).forEach(function(file) {
const existingFile = findFile(file)
if (existingFile) {
console.error('Existing file: ', existingFile)
return
}
existingFiles.push(file)
console.warn('Added file: ', file)
})
})
<input type="file" />
I think you're running into issues with how your assigning your files to the dom. Remember FileLists are read only, meaning you can't select multiple files then keep going and append them to an existing element.
But you CAN append them to a JavaScript array:
files=[]; files.push(fileList);
So, I've edited your JSFiddle to include this functionality, as well as the check you were asking for:
https://jsfiddle.net/Lc5gb7c9/3/
I would recommend you look at:
http://blog.teamtreehouse.com/uploading-files-ajax for the way to upload via Ajax, as you'll need to create the formData object and then loop through your uploaded_files array and append them to the correct formData key. They are getting file from the html element, but you already have file in the uploaded_files array, so you would do it like:
for (var i = 0; i < uploaded_files.length; i++) {
formData.append('files[]', uploaded_files[i], uploaded_files[i].name);
}
Once that's done, you can make your ajax call.
I would like to upload multiple files in Salesforce using visualforce.
I can upload one file at a time.
But my requirement is, i want to display only one "add a file" button in visualforce page, when clicked over that button browse window should open and user selects a particular file and adds it. But after adding a file, the file path should be displayed as well as the same "add a file" button should be displayed below that which allows us to add another file. And after that we can save what we have added. It is same as adding attachments in our email.
Any help regarding this will be appreciated.
<!-- Use uploadFile function to attach multiple attachment.Update hardcoded parent id.-->
<apex:page>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
var __sfdcSessionId = '{!GETSESSIONID()}';
var filesToUpload = [];
var uploadedFile = 0;
</script>
<style>
.FilebuttonStyle{
font-family:Arial,'Helvetica Neue',Helvetica,sans-serif;
font-size:13px`enter code here`;color:#ffffff;
background-color: #169fcc !important;
text-decoration:none;
text-align:center;
border:1px solid #1691ba !important;
line-height: 25px;!important;
border-radius:4px;
display:inline-block;
cursor:pointer;
width:85px;
}
td.fileRow {
overflow: hidden;
font-family:Arial,'Helvetica Neue',Helvetica,sans-serif;
font-size:13px;color:#ffffff;
background-color: #8db728;
text-decoration:none;
text-align:center;
border:1px solid #6c8049;
line-height: 32px;!important;
border-radius:4px;
//padding-left:10px;
//padding-right:10px;
background-image:linear-gradient(top,#9dcc3d,#7da223);
background-image:-o-linear-gradient(top,#9dcc3d,#7da223);
background-image:-moz-linear-gradient(top,#9dcc3d,#7da223);
background-image:-webkit-linear-gradient(top,#9dcc3d,#7da223);
background-image:-ms-linear-gradient(top,#9dcc3d,#7da223);
display:inline-block;
cursor:pointer;
width:120px;
overflow: hidden;
}
td.fileRow input {
display: block !important;
width: 157px !important;
height: 57px !important;
opacity: 0 !important;
overflow: hidden !important;
}
.fileCheckBox {
width: 16px;
height: 16px;
display: inline-block;
margin: 3px 5px 3px 3px;
background-color: white;
//box-shadow: 0px 0px 1px #b0b3ae;
text-align: center;
vertical-align: top;
}
.FilebuttonGroup{
float:right;
padding-right: -70px!important;
}
</style>
<script src="/soap/ajax/32.0/connection.js" type="text/javascript"></script>
<script type="text/javascript">
function uploadFile(parentId)
{
// var input = $('.fileInput')[0];
//var input = document.getElementById("file-input");
// var filesToUpload = input.files;
$("input[type=file]").each(function(){
filesToUpload.push($(this)[0].files[0]);
});
//console.log(filesToUpload);
for(var i = 0, f; f = filesToUpload[i]; i++)
{
var reader = new FileReader();
// Keep a reference to the File in the FileReader so it can be accessed in callbacks
reader.file = f;
reader.onload = function(e)
{
var att = new sforce.SObject("Attachment");
att.Name = this.file.name;
att.ContentType = this.file.type;
att.ParentId = parentId;
var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++)
{
binary += String.fromCharCode(bytes[i]);
}
att.Body = (new sforce.Base64Binary(binary)).toString();
sforce.connection.create([att],
{
onSuccess : function(result, source)
{
if (result[0].getBoolean("success"))
{
console.log("new attachment created with id " + result[0].id);
}
else
{
console.log("failed to create attachment " + result[0]);
}
},
onFailure : function(error, source)
{
console.log("an error has occurred " + error);
}
});
};
reader.readAsArrayBuffer(f);
}
}
function addRow(tableID){
var row = '<tr><td><input type="checkbox" onclick="processCheckbox()" name="chk" class="fileCheckBox"/</td><td class="fileRows"><input type="file"/> </td></tr>';
$('#'+tableID).append(row);
}
function deleteRow(tableID)
{
try
{
var table=document.getElementById(tableID);
var rowCount=table.rows.length;
for(var i=0;i<rowCount;i++)
{
var row=table.rows[i];
var chkbox=row.cells[0].childNodes[0];
if(null!=chkbox&&true==chkbox.checked)
{
table.deleteRow(i);
filesToUpload.splice(i, 1);
// console.log(filesToUpload);
rowCount--;
i--;
}
}
processCheckbox();
}
catch(e)
{
alert(e);
}
}
function processCheckbox(){
$("[id$='_remove']").hide();
var checkCount=0;
$("#dataTable input[type='checkbox']").each(function(){
if($(this).is(':checked'))
{
checkCount++;
}
});
if(checkCount >0){
$("[id$='_remove']").show();
}
}
</script>
<div class="FilebuttonGroup">
<input type="button" value="Delete Row" id="_remove" onclick="deleteRow('dataTable')" class="FilebuttonStyle" title="Delete Row"/>
<input type="button" value="Add Row" onclick="addRow('dataTable')" id="_add" class="FilebuttonStyle" title="Add Row"/>
</div>
<table id="dataTable" >
<tbody>
<tr>
<td> </td>
<td class="fileRows"> <input type="file" class="fileInput"/> </td>
<td></td>
</tr>
</tbody>
</table>
<!--Correct this attachment parentid -->
<input type="button" value="Upload" onclick="uploadFile('5009000000cjeZn')" title="Upload"/>
<div id="statusid"></div>
<script>
$(document).ready(function(){
$("[id$='_remove']").hide();
$("[id$='attachmentBlock']").find('.pbSubsection').attr({'style':'margin-right:-70px !important;'});
});
</script>
</apex:page>
You can upload multiple attachment using ajax asynchronously. You need to update the parent record id of attachment. Find the code at:
https://github.com/DebGit/Dev_2015_org1/blob/master/src/pages/FileUploaderAjax.page