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);
}
});
Related
I am selecting multiple images using html tag 'input file multiple html' as below.
#Html.TextBoxFor(model => model.files, "",
new {#id = "filesToUploadID", #type = "file", #multiple = "multiple" })
<div class="col-md-10" id="selectedFiles"></div>
Then in javascript, I attached 'onchange' event listner to the above tag. When I select multiple images, I get all the attached images to the tag using jquery. But I need image file names as well. While getting image file names, I get only one file name poplulated in my html along with image using jquery.
jquery/ javascript is below
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#filesToUploadID').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#selectedFiles");
}
function handleFileSelect(e) {
debugger;
NameArray = [];
if (!e.target.files) return;
selDiv.innerHTML = "";
var files = e.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
NameArray.push(f.name);
var reader = new FileReader();
reader.onload = function (e) {
var html = "<img src='" + e.target.result + "' />";// + "<div>" + + "</div>";//+ "<br clear=\"left\"/>";
$(selDiv).append($(html));
//selDiv.innerHTML += html;
}
reader.readAsDataURL(f);
}
}
I tool help from this link and implemented both ways but could not succeed.
All images names are relevant to the images. What I am getting is like this
It's source code is
I have to assign id's based on image names that's why it is important to get relevant image names. Any lead to the topic will be high appreciated.
Thank you.
var f = files[i];
var fileName = e.target.f.name
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.
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?
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/
my problem is when I select the multiple images it displaying correct, and I am storing this in one array, from that array I need to get the image name. right now it's working but in setOfImages array all image name is same. i need to take the image URL also when i put that setOfImages array in map function that URL are get repeating this are two problems I am facing if not clear put console.log(setOfImages) and console.log(imageUrl),
imagetrigger(e){
var setOfImages =[], imageUrl=[];
for (var i = 0; i < e.target.files.length; 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]
});
$('.image').remove();
for(var j = 0; j<setOfImages.length; j++) {
$('.placeholder').prepend('<div class="image"><img src="data:image/jpeg;base64,'+ setOfImages[j].image +'" /></div>');
}
setOfImages.map(function(){
imageUrl.push(el.fileName);
})
console.log(imageUrl)
}
reader.readAsDataURL(file);
}
}
Just add parameter el to your map.
setOfImages.map(function(){
imageUrl.push(el.fileName);
})
Change like this.
setOfImages.map(function(el){
imageUrl.push(el.fileName);
})