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?
Related
I am working on a django app in which the html code called tool.hmtl along with the javascript code called myscripts.js let the user upload the folder and then do some processing on that data. Relevant section of tool.hmtl is given as follows.
<main class="tool mg-t-900">
<div id="folderUploadDiv">
<h1 class="tool__heading | text-center text-capitalize">
Upload your folder here
</h1>
<label
for="folder"
class="tool__upload | flex flex-center flex-column mg-t-500 text-center"
>
<i class="ri-upload-cloud-line tool__icon"></i>
<p class="tool__txt text-capitalize">Browse folder to upload</p>
</label>
<input type="file" id="folder" webkitdirectory multiple />
.............some code......
<script src="{% static 'myscripts.js' %}"></script>
<script src="{% static 'app.js' %}"></script>
<script>
const fileInput = document.querySelector("#folder");
const loder = document.querySelector(".loder");
const toggleLoder = function () {
loder.classList.add("active");
setTimeout(() => {
loder.classList.remove("active");
}, 30000);
startTypingAnimation();
};
fileInput.addEventListener("change", toggleLoder);
function startTypingAnimation() {
new TypeIt("#loder-text", {
strings: "Your file is being prepared...",
speed: 75,
loop: true,
}).go();
}
</script>
<script>
setTimeout(function () {
location.reload();
}, 300000); // refresh every 5 minutes (300000 milliseconds)
</script>
</body>
</html>
{% endblock %}
and relevant section of myscripts.js is as under.
// const axios = require('axios');
$("#folderUploadDiv").show();
$("#selectorDiv").hide();
username = "";
contentType = "";
var dataToSend = []
var flag=1
document.getElementById("folder").addEventListener("change", function(event) {
var output = document.querySelector("ul");
var files = event.target.files;
var jsonFiles =0;
var rightOrderFiles = [];
for (var i=0; i<files.length; i++) {
var item = document.createElement("li");
var innerFiles = files[i].webkitRelativePath.split("/");
if(innerFiles.length ===4){
jsonFiles++;
rightOrderFiles.push(files[i].webkitRelativePath)
var reader = new FileReader();
reader.onload = onReaderLoad;
reader.readAsText(files[i]);
}
// console.log("file path : ", files[i].webkitRelativePath);
item.innerHTML = files[i].webkitRelativePath;
output.appendChild(item);
};
}, false);
In this code snippets (both HTML and Javascript), we can see that user uploads the folder and then some processing is done in Javascript.
My question is, how can I change the code both in tool.hmtl along with the javascript code myscripts.js such that the user uploads a zip file and a folder is extracted from that zip file rather than user uploading the folder itself. Everything else remain the same, the only change needed is let the user upload zip file instead of the folder directly and the folder is then extracted from the zip file.
To change the code to extract a folder from a zip file, you need to make the following changes in both tool.html and myscripts.js:
1- In tool.html, change the type of the file input to "file" instead of "folder".
<input type="file" id="folder" />
2- In myscripts.js, use a library such as jszip.js to extract the contents of the uploaded zip file. You can add the library to your project by including the following line in the head of tool.html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.2.2/jszip.min.js"></script>
3- Replace the event listener for the file input with the following code:
document.getElementById("folder").addEventListener("change", function(event) {
var output = document.querySelector("ul");
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function (e) {
var zip = new JSZip();
zip.loadAsync(e.target.result)
.then(function (zip) {
var rightOrderFiles = [];
var jsonFiles = 0;
zip.forEach(function (relativePath, file) {
if (relativePath.split("/").length === 4) {
jsonFiles++;
rightOrderFiles.push(relativePath);
file.async("text").then(function (content) {
var item = document.createElement("li");
item.innerHTML = relativePath;
output.appendChild(item);
});
}
});
});
};
reader.readAsArrayBuffer(file);
}, false);
This code uses JSZip to load the contents of the uploaded zip file, extract the files and process them in the same manner as before.
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:
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 have a form that allows users to upload multiple images. Users has an option to remove Images one by one if they don't want to upload that particular image.
Now, How to remove the value from the file type of the one that they removed (e.g. didn't want to upload)?
I have tried using ($('input').val("")) but it works only for single image not for multiple images. If I used this for multiple image then all uploaded images value become empty instead of that particular image that user want to remove.. Below is my Code:-
HTML
<input type="file" id="files2" name="cert_img" multiple>
<output id="list2"></output>
Javascript
var count2=0;
function handleFileSelect2(evt) {
var $fileUpload = $("input#files2[type='file']");
count2=count2+parseInt($fileUpload.get(0).files.length);
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function (theFile) {
return function (e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" id="image_X" src="', e.target.result, '" title="', escape(theFile.name), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('list2').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
$('#files2').change(function(evt){
handleFileSelect2(evt);
});
$('#list2').on('click', '.remove_img_preview',function () {
$(this).parent('span').remove();
//$('input').val("");
});
Thanks in advance..
According to this question you can't change FileList content because it is readonly.
But if you want to remove a file of FileList, you can create a new object and set to it files that you want to upload. Then use created object to upload files. Run my example and select multiple files. Then click on any file that you want to delete. After delete files, see browser console.
var files;
$("#files").on("change", function(e){
files = $("#files")[0].files;
$.each(files, function(index, value){
$("ol").append("<li data-index='"+index+"'>"+ value.name +"</li>");
});
});
$(document).on("click", "li", function(){
var newFiles = {};
var index = $(this).index();
$("li:nth-child(" + (index + 1) + ")").remove();
$("li").each(function(index, element){
var dataIndex = $(element).attr("data-index");
newFiles[index] = files[dataIndex];
});
console.log(newFiles);
});
li:hover {
color: red;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="files" multiple>
<ol></ol>
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);
}
});