Read input field files when seperate button is clicked - javascript

With the following input field, the user submits one or multiple HTML files.
<input type="file" id="inputfield" accept="text/html" multiple/>
<div id="get-files">Get Files</div>
When get-files is clicked, how can I get the content of each file on the input field and mess with each file content using the fileReader API?
I tried the following but receive no errors or content.
$("#get-files").on("click", function() { getFilesContent(); });
function getFilesContent() {
var pages = $("#inputfield")[0].files;
// get files data
for (var i = 0; i < pages.length; i++) {
var reader = new FileReader();
reader.onload = (function() {
return function(e) {
console.log($("#inputfield")[0].result);
}
});
reader.readAsText(pages[i]);
}
}

Try this instead
function getFilesContent() {
var pages = $("#inputfield")[0].files;
for (let i = 0; i < pages.length; i++) {
let reader = new FileReader();
reader.onload = function() {
console.log(reader.result);
}
reader.readAsText(pages[i]);
}
}
reader.result contains your HTML data.

Related

How do I know the total number of downloaded files type = "file" multiple?

There is a problem that if you select files individually, only the last selected one will be sent, if you select several files and send them, then everything is fine - several files will be sent.
How do I know the total number of downloaded files type = "file" multiple?
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
console.log(filesAmount);
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
let selectedFile = input.files[i];
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
$($.parseHTML('<div>')).text(selectedFile.name).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(selectedFile);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
Upload files one at a time:
Download multiple files at once:

multiple image in angularjs

i want to upload multiple image in angular.i have uploaded multiple image but when i click submit button i could get my files name in my console like
my view page like
<form ng-submit="save()"><input type="file" name="images" id="images" ng-model="images" onchange="angular.element(this).scope().imageUpload(event)" multiple><input type="submit"></form>
my controller like below
$scope.files = [];
$scope.imageUpload = function(event){
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = function(e){
$scope.$apply(function() {
$scope.files.push(e.target.result);
});
}
reader.readAsDataURL(file);
}
}
when i click submit button my code look like below and my console looks like in above picture
$scope.save = function(){
console.log($scope.files);
}
how can i send all selected images to php file in angularjs?

react js multiple image upload with preview

using react js I need multiple image upload with preview I tried with below code is not working it showing me error in console
Uncaught DOMException: Failed to set the 'value' property on
'HTMLInputElement': This input element accepts a filename, which may
only be programmatically set to the empty string.
uploadImage(e){
var numFiles = e.target.files.length;
for (var i = 0, numFiles = e.target.files.length; i < numFiles; i++){
var file = e.target.files[i];
if(!file.type.match('image'))
continue;
var reader = new FileReader();
reader.onload = function(e) {
setOfImages.push({
fileName:file.name,
image:e.target.result.split(',')[1]
});
for(var j = 0; j<setOfImages.length; j++) {
$('.placeholder-blk').prepend('<div class="image-placeholder"><img src="data:image/jpeg;base64,'+ setOfImages[j].image +'" /></div>');
}
console.log(setOfImages);
}
reader.readAsDataURL(file);
}
}
<input type="file" name="image-uploder" id="image-uploder" className="file-loader" onChange={this.uploadImage.bind(this)} multiple />
Did you try adding the value to the state and populate the name from the state.
Something like
<input type="file" name={this.state.setOfImages} id="image-uploder" className="file-loader" onChange={this.uploadImage.bind(this)} multiple />
and inside your function populate the state.
this.setState({setOfImages: JSON.stringify(setOfImages)})
something like this.
export class Demo extends React.Component{
constructor(props){
super(props)
this.state = {
setOfImages : []
}
}
setOfImages(event){
event.preventDefault();
this.setState({
setOfImages: ["hello", "hi"]
})
}
render(){
return (
<div>
<input value={this.state.setOfImages}/>
<button onClick={this.setOfImages.bind(this)}/>
</div>
)
}
}
Now first the input will be populated with empty array . When you click the button the state will change by setting the setOfImages = ["hello", "hi"] and making the input value set to those values.
This makes no sense $('.placeholder-blk').remove(); then subsequently try to prepend to that? It's gone.
And here only the first file?
var file = e.target.files[0];
Did you mean to process the files
var numFiles = e.target.files.length;
for (var i = 0, numFiles = e.target.files.length; i < numFiles; i++)
{ var file = e.target.files[i]; .. }
Ref here how to do it raw: developer.mozilla.org/en-US/docs/

Using FileReader.onprogress to display progress when hashing a file (SHA256)

I am using Forge Crypto Library to hash (SHA256) an uploaded file and output a digest. The file is being hashed fine. But if it is a large file then hashing it might take a little while. So I am trying to display a percentage complete field using FileReader.onprogress. I tried to implement it, but the progress is not being shown. It is just displaying 100.
HTML:
<input id="fileInput" type="file"/>
<label id="label"></label>
JS:
$("#fileInput").change(function() {
hashFiles(this.files);
});
function hashFiles(files) {
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
reader.onload = function() {
var sha256 = forge_sha256(reader.result, reader.result.length);
alert("SHA256 is " + sha256);
};
reader.onerror = function() {
alert("Could not read the file");
};
var currentFile = files.item(i);
reader.onprogress = function(currentFile) {
if (currentFile.lengthComputable) {
var progress = parseInt(((currentFile.loaded / currentFile.total) * 100), 10);
document.getElementById('label').innerHTML = progress;
}
}
reader.readAsBinaryString(files.item(i));
}
}
http://codepen.io/cavanflynn/pen/vNQPgd?editors=101
Am I implementing .onprogress correctly? I don't think I need the currentFile variable, but I can't figure out how to correctly implement it. Thanks!

HTML5 File API - Send file to server for processing

I have form with the following form:
<form>
...
<input type="file" multiple="multiple" id="images" />
<a id="add">Add</a>
...
<input type="submit" value="Submit" />
</form>
The add element's click event is then wired up like so:
var images = [];
$("#add").click(function() {
var files = $("#images")[0].files;
for (var i = 0; i < files.length; i++) {
images.push[files[i];
}
$("#images").val("");
});
This allows me to add the images from multiple locations. Now I need to send the files back to the server. I found the following question:
Passing path to uploaded file from HTML5 drag & drop to input field
Which seems to be similar. Therefore I used the following to wire up an event when the form is submitted:
var form = $("form");
form.submit(function() {
for (var i = 0; i < images.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
$("<input>").attr({ type: "hidden", name: "images[]" }).val(e.target.result).appendTo(form);
};
reader.readAsDataURL(images[i]);
}
});
Finally on the server I have the following code:
print_r($_POST);
print_r($_FILES);
However neither collection contains an item for the images submitted. I was wondering what I am doing wrong? Thanks
Alright, I think your problem here is being caused by the FileReader's load event handler, which appends those data URLs to the form, being called after the form is submitted to the server.
You could solve this problem, and do away with the superfluous images variable and submit event handler by adding these items to the form in the click handler for the Add link. You can also use this opportunity to do a little client side validation, preventing duplicate data URLs from being uploaded to the server, and even to add a preview/remove option for the selected images.
Furthermore, you could do away with the Add link by replacing its click handler with a change handler attached to your file input.
Edit (nfplee):
var images = [];
$("#add").click(function() {
var files = $("#images")[0].files;
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
images.push({ name: file.name, file: e.target.result });
};
})(files[i]);
reader.readAsDataURL(files[i]);
}
$("#images").val("");
});
var form = $("form");
form.submit(function() {
for (var i = 0; i < images.length; i++) {
$("<input>").attr({ type: "hidden",
name: "images[" + i + "][name]" }).val(images[i].name).appendTo(form);
$("<input>").attr({ type: "hidden",
name: "images[" + i + "][file]" }).val(images[i].file).appendTo(form);
}
});

Categories