How to select multiple files with <input type=file>?
New answer:
In HTML5 you can add the multiple
attribute to select more than 1 file.
<input type="file" name="filefield" multiple="multiple">
Old answer:
You can only select 1 file per
<input type="file" />
. If you want to
send multiple files you will have to use multiple input tags or use
Flash or Silverlight.
How can I set preview of multiple video file, by selecting from input type='file'
You should better use createObjectURL in this case.
document.querySelector("input[type=file]").onchange = function(event) {
var numberOfVideos = event.target.files.length;
for (var i = 0; i < numberOfVideos; i++) {
var file = event.target.files[i];
var blobURL = URL.createObjectURL(file);
var video = document.createElement('video');
video.src = blobURL;
video.setAttribute("controls", "")
var videos = document.getElementById("videos");
videos.appendChild(video);
}
}
video{width: 500px}
<input type="file" name="video" multiple>
<div id="videos"></div>
Preview images before upload
Here is jQuery version for you. I think it more simplest thing.
$(function() { // Multiple images preview in browser var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) { var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) { var reader = new FileReader();
reader.onload = function(event) { $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview); }
reader.readAsDataURL(input.files[i]); } }
};
$('#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>
How to add/upload/choose multiple files from one input tag?
You can hide the input[type=file] and provide an UI that interacts with the input in order to select new files and manage separately a list of files.
So you can:
add a hidden input
<input id="myInput" type="file" multiple style="display:none" />
Provide a good looking UI with a button that calls the myInput.click() in order to open the prompt
subscribe to input change event and get the myInput.files and store them in an array or collection
to upload all files via AJAX just create a FormData and append all the files then pass FormData instance to the ajax call (eg: $ajax({...data: formData...})).
EDITED:
Plnkr link
Sample Behavior:
- Pressing "+ Add Files" button will add new files to the list.
- Clicking a file in the list will remove the file
- Pressing "Send Files" button will send the files to the corresponding URL
Sample HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input id="myInput" type="file" multiple style="display:none" />
<button id="myButton" type="button" style="border-radius: 5px; background-color: #fff; color: green;">+ Add Files</button>
<button id="mySubmitButton" type="button" style="border-radius: 5px; background-color: #fff; color: green;">Send Files</button>
<div id="myFiles"></div>
</body>
</html>
Sample Script:
$(function(){
let inputFile = $('#myInput');
let button = $('#myButton');
let buttonSubmit = $('#mySubmitButton');
let filesContainer = $('#myFiles');
let files = [];
inputFile.change(function() {
let newFiles = [];
for(let index = 0; index < inputFile[0].files.length; index++) {
let file = inputFile[0].files[index];
newFiles.push(file);
files.push(file);
}
newFiles.forEach(file => {
let fileElement = $(`<p>${file.name}</p>`);
fileElement.data('fileData', file);
filesContainer.append(fileElement);
fileElement.click(function(event) {
let fileElement = $(event.target);
let indexToRemove = files.indexOf(fileElement.data('fileData'));
fileElement.remove();
files.splice(indexToRemove, 1);
});
});
});
button.click(function() {
inputFile.click();
});
buttonSubmit.click(function() {
let formData = new FormData();
files.forEach(file => {
/* here I just put file as file[] so now in submitting it will send all
files */
formData.append('file[]', file);
});
console.log('Sending...');
$.ajax({
url: 'https://this_is_the_url_to_upload_to',
data: formData,
type: 'POST',
success: function(data) { console.log('SUCCESS !!!'); },
error: function(data) { console.log('ERROR !!!'); },
cache: false,
processData: false,
contentType: false
});
});
});
Remove a FileList item from a multiple input:file
I' am afraid that you cannot delete objects from FileList object
directly. Just assign $('input:file#upload')[0].files
to an Array
and then remove items from that array using splice
or method of your choice and then use that Array
.
Angular File Upload
Here is a working example for file upload to api:
Step 1: HTML Template (file-upload.component.html)
Define simple input tag of type file
. Add a function to (change)
-event for handling choosing files.
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="handleFileInput($event.target.files)">
</div>
Step 2: Upload Handling in TypeScript (file-upload.component.ts)
Define a default variable for selected file.
fileToUpload: File | null = null;
Create function which you use in (change)
-event of your file input tag:
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
If you want to handle multifile selection, than you can iterate through this files array.
Now create file upload function by calling you file-upload.service:
uploadFileToActivity() {
this.fileUploadService.postFile(this.fileToUpload).subscribe(data => {
// do something, if upload success
}, error => {
console.log(error);
});
}
Step 3: File-Upload Service (file-upload.service.ts)
By uploading a file via POST-method you should use FormData
, because so you can add file to http request.
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = 'your-destination-url';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.httpClient
.post(endpoint, formData, { headers: yourHeadersConfig })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
So, This is very simple working example, which I use everyday in my work.
How to allow <input type=file> to accept only image files?
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>
Related Topics
Relative Paths in JavaScript in an External File
Retrieving Html5 Video Duration Separately from the File
How to Convert a Dom Node List to an Array in JavaScript
Uploading 'Canvas' Image Data to the Server
Convert HTML to Data:Text/Html Link Using JavaScript
JavaScript Dom: Find Element Index in Container
JavaScript At Bottom/Top of Web Page
How to Make a Jquery "$.Post" Request Synchronous
Programmatically Trigger "Select File" Dialog Box
How to Detect Which One of the Defined Font Was Used in a Web Page
Conditionally Load JavaScript File
Fetch(), How to Make a Non-Cached Request
Any Way to Clone Html5 Canvas Element With Its Content
Using Execcommand (JavaScript) to Copy Hidden Text to Clipboard