I have a file upload button, and I want to get the path of selected file.
Here's my code:
var pniotApp = angular.module('pniotApp', []);
pniotApp.controller('pniotCtrl', function ($scope, $http, $location) {
var temp = [];
Array.prototype.push.apply(temp, element.files);
for (i = 0; i < temp.length;i++)
$scope.fileBuffer.push(temp[i])
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body dir="rtl" ng-app="pniotApp" ng-controller="pniotCtrl">
<input id="uploadFile" type="file" class="filestyle" data-classButton="btn btn-primary" multiple data-input="false" data-classIcon="icon-plus" onchange="angular.element(this).scope().fileSelected(this)" data-buttonText="uplaod...">
</body>
Note: I'm using 'temp' because element.files doesn't behave like an normal array.
How can I get the relative path of the files?
I tried to do this
document.getElementById("uploadFile").value
But I get just the path of the first file.
What can I do?
You can't access the path for security reasons but since you are satisfied with .value for a single entry, I will assume you mean the file name.
A file input will have a files property that contains a list of the selected files (you can loop over it like an array). The objects inside each have a name property that will give you the file name.
document.querySelector("input").addEventListener("change", list_files);
function list_files() {
var files = this.files;
for (var i = 0; i < files.length; i++) {
console.log(files[i].name);
}
}
<input type="file" multiple>
Related
I using js to create my form, my problem is how to just select directory, not file?
Belows is my coding:
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
customBtn.addEventListener("click", function() {
realFileBtn.click();
});
realFileBtn.addEventListener("change", function() {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value;
} else {
customTxt.innerHTML = "No file chosen, yet.";
}
});
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
Below is my output:
Actually I want the output not to select the file, just select the folder, because the next step I need store file in this folder directory.
If success the output is folder directory name is:
C:\Staff Import Folder\Source
Hope someone can help me solve this problem. Thanks.
In newest browsers, you can select a directory content with the webkitdirectory attribute of the <input type="file"> element, as being defined by Files and Directories entries API, but I fear this will be deceptive to you since it will only select all the files in this directory (and its sub-folders). There is currently no way to navigate this directory from here.
We should be able to navigate such directory, by looking at the webkitEntries IDL attribute, but currently browsers only populate this from a drop event. You can see a demo in this Q.A.
inp.onchange = (e) => {
console.log( inp.webkitEntries ); // []
console.log( [...inp.files].map( file => file.name ) );
};
<input type="file" webkitdirectory id="inp">
But even then, while you'll be able to navigate that directory, you still won't be able to set anything on the FileSystem. Web scripts simply don't have the authorization to write anything on the disk, except in sand-boxed areas like IndexedDB.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory
document.getElementById("filepicker").addEventListener("change", function(event) {
let output = document.getElementById("listing");
let files = event.target.files;
for (let i = 0; i < files.length; i++) {
let item = document.createElement("li");
item.innerHTML = files[i].webkitRelativePath;
output.appendChild(item);
};
}, false);
<input type="file" id="filepicker" name="fileList" webkitdirectory multiple />
<ul id="listing"></ul>
I want to give the user the possibility to upload multiple files during multiple stages which will be processed in my flask backend upon uploading. Therefore I have a multiple file input form in my HTML:
<form action="/do-stuff" method="POST" enctype="multipart/form-data">
<label id="file-uploader-label" for="file-uploader">Upload Files</label>
<input id="file-uploader" type="file" name="file" accept="image/*" multiple="true" required>
<button id="btn-upload" type="submit">Upload</button>
</form>
I display all files in a table (not shown above) and give the user the possibility to remove items from the file list as follows:
let fileList = new Array;
const fileUploader = this.document.getElementById('file-uploader');
let uniqueid = 1;
fileUploader.addEventListener('change', function () {
for (let i = 0; i < fileUploader.files.length; i++) {
let currFile = fileUploader.files[i];
fileList[uniqueid] = currFile;
// Removal and display code
uniqueid++;
}
});
This leaves me with the fileList of type "FileList" containing all desired files. Whenever I upload the file-uploader will only use the latest / most recently uploaded files and not all.
Having the complete list - is there a way in javascript to append to the files contained in the file-uploader or a workaround to pass the data to my flask backend (werkzeug.datastructures.FileStorage type)?
Thanks in advance :)
Once you have a complete list of files that you want to upload, you can make a POST request from JavaScript to your Flask endpoint to store the files.
With a minimal form
<form id="form-files">
<input id="file-input" type="file" multiple=true />
<button type="submit">Submit</button>
</form>
You can intercept the form submit action and send the files to a Flask endpoint. The fileList array comes from your file upload/remove logic.
var formFiles = document.getElementById('form-files');
formFiles.addEventListener('submit', function(e) {
e.preventDefault();
var formData = new FormData();
var request = new XMLHttpRequest();
for (var i = 0; i < fileList.length; i++) {
formData.append('files[]', fileList[i]);
}
request.open('POST', '/upload');
request.send(formData);
});
Finally write a flask upload endpoint that processes (stores) the files.
#app.route("/upload", methods=["POST"])
def upload():
uploaded_files = request.files.getlist("file[]")
# Store files
This question already has answers here:
How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?
(14 answers)
Closed 6 years ago.
I have a select choice of files to upload can be single or multiple
as I select I would like to have a text below stated the path of the files I have selected.
<form action="mymethod" enctype="multipart/form-data" method="Post" id="submitForm">
<input id="file" name="file[]" multiple type="file">
Upon selecting the file let say its 3:
it will show on the screen:
however currently it is showing:
here is my script:
<script>
var selDiv = "";
document.addEventListener("DOMContentLoaded", init,
false);
function init() {
document.querySelector('#file').addEventListener(
'change', handleFileSelect, false);
selDiv = document.querySelector("#selectedFiles");
}
function handleFileSelect(e) {
if (!e.target.files)
return;
selDiv.innerHTML = "";
var files = e.target.files;
for ( var i = 0; i < files.length; i++) {
var f = files[i];
selDiv.innerHTML += f.name + "<br/>";
}
}
</script>
Prehaps you guys could give me suggestion on how I would tackle this issue?
You won't be able to access this via JavaScript; as a security precaution the browser will expose the file name to you, but nothing else about the local file system.
This is a built in security measure by the browser creators, so private information about local file paths cannot be seen.
I am trying to implement a JavaScript program to read a bunch of CSV files from a particular directory containing sub-directories. To do so, I am thinking of using Javascript to read multiple files using webkitdirectory and reading the files and then using java to push them.
HTML Form
<input id="csv" type="file" multiple webkitdirectory directory>
<input type="button" onclick="readCSV()" value="Submit">
JavaScript to Read Files
function readCSV(){
var fileInput = document.getElementById("csv");
var fileCount = fileInput.files.length;
if( fileCount != 0) {
alert(fileCount);
var reader;
for (var i = 0; i < fileCount; i++) {
reader = new FileReader();
reader.onload = function () {
document.getElementById('out').innerHTML = reader.result;
// Once the file is read, Send it to JavaServlet to save on server.
};
reader.readAsBinaryString(fileInput.files[i]);
}
} else {
alert("Select a File");
}
}
The problem I am facing here is that the code runs successfully when only one file is selected but breaks when multiple files are selected. I think the problem is in sync read. But I couldn't find a way to either sync read or pause the loop while the reader object completely reads the file.
I have a form, which allows to select an item from a dropdown list and upload a file. The name and the ID of the item are saved in a Spreadsheet document. Works with one file...but I want to upload multiple files. Could you help me fixing the script?
The HTML part looks like this
<div class="col-md-4 col-sm-6 ">
<div class="caption">
<h3>Bildauswahl</h3>
<p align="center"><input type="file" name="myFiles[]" id="myFiles" multiple></p>
</div>
</div>
My script, which is not working, is the following:
var dropBoxId = "XYZ";
var logSheetId = "ABC";
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('InputForm.html');
}
function uploadFiles(formObject) {
try {
// Create a file in Drive from the one provided in the form
var folder = DriveApp.getFolderById(dropBoxId);
var input = document.getElementById('myFiles');
for (i = 0; i<input.files.length; i++) {
var blob = input.files[i];
var file = folder.createFile(blob);
var ss = SpreadsheetApp.openById(logSheetId);
var sheet = ss.getSheets()[0];
sheet.appendRow([file.getName(), file.getUrl(), formObject.myName]);
}
// Return the new file Drive URL so it can be put in the web app output
return file.getUrl();
} catch (error) {
return error.toString();
}
}
Thanks.
As of right now you have to use a work around to work with multiple files. The multiple attribute only works in IFRAME mode, but file inputs are broken in IFRAME mode.
To see this workaround take a look at the bug submission for this issue:
https://code.google.com/p/google-apps-script-issues/issues/detail?id=4610
Also in your code you have some mixing of server side and client side code that will not work:
var folder = DriveApp.getFolderById(dropBoxId); //server side
var input = document.getElementById('myFiles'); //client side
You will need to do your multiple file processing on the client side
I came up with a nice solution for multi-file uploading. Limitations are files must be under 10 MB.
CODE.GS
function doGet() {
return HtmlService.createHtmlOutputFromFile('index').setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function saveFile(data,name,folderId) {
var contentType = data.substring(5,data.indexOf(';'));
var file = Utilities.newBlob(Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)), contentType, name);
DriveApp.getFolderById(folderId).createFile(file);
}
index.html
<div>
<input type="file" id="myFiles" name="myFiles" multiple/>
<input type="button" value="Submit" onclick="SaveFiles()" />
</div>
<script>
var reader = new FileReader();
var files;
var fileCounter = 0;
var folderId = "";
reader.onloadend = function () {
google.script.run
.withSuccessHandler(function(){
fileCounter++;
postNextFile();
}).saveFile(reader.result,files[fileCounter].name,folderId);
}
function SaveFiles(){
var folderSelect = document.getElementById("folderSelectId");
folderId = folderSelect.options[e.selectedIndex].value;
files = document.getElementById("myFiles").files;
postNextFile();
}
function postNextFile(){if(fileCounter < files.length){reader.readAsDataURL(files[fileCounter]);}else{fileCounter=0;alert("upload done")}}
</script>