Is there any way to change choosen file name?
For example, I choose a file name img1. On choosing the file it have to change to dynamicname. Is there any way to change name?
<input type="file" fd-input/>
Here is a way to change a filename inside a directive:
app.directive('file', function() {
return {
scope: {
file: '='
},
link: function(scope, el, attrs) {
el.bind('change', function(event) {
var files = event.target.files;
var file = files[0];
scope.file = 'New file name';
scope.$apply();
});
}
};
});
Use it as following:
<input type="file" file="param.file" />
JSFiddle demo
If you have access to FormData you can use append method to change file name.
Refer this doc for more information.
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
var data = new FormData();
var ext = files[0].name.match(/\.(.+)$/)[1];
var fileName = Math.random().toString(36).substr(2, 19) + "." + ext;
// Add the uploaded image content to the form data collection
if (files.length > 0) {
//data.append("UploadedImage", files[0]); //if you want to pass default name
data.append("UploadedImage", files[0],fileName);
}
HTML code -
<input id="fileUpload" type="file" ng-file-accept="'.jpg , .jpeg ,.bmp , .gif ,.png'" accept="image/*" />
Related
I am trying to read a csv file with jquery. I have passed the file with input tag of html but i am having some problems to read it. Below the code that i have written.
HTML code:
<div id="insertCSV" class = "formblacktransparent">
<input id="csv" type="file" accept=".csv" class="form-control" placeholder="Insert csv"> </input>
<button type="button" class="log-btn" id="confCsv"> Confirm </button>
</div>
Jquery code:
$("#confCsv").click(function(data){
var input = document.getElementById('csv');
var file = input.files[0];
alert(file[0]);
var fr = new FileReader();
fr.readAsDataURL(data);
alert(fr);
});
I don 't understand if in this way the file has been uploaded and how i can accede to it.
Any ideas? thank you in advance!!
I write below the code that i have used to resolve my problem. I hope it can be useful. Hello!
document.querySelector("#confCsv").addEventListener('click', function() {
if(document.querySelector("#csv").files.length == 0) {
alert('Error : No file selected');
return;
}
// first file selected by user
var file = document.querySelector("#csv").files[0];
// perform validation on file type & size if required
// read the file
var reader = new FileReader();
// file reading started
reader.addEventListener('loadstart', function() {
console.log('File reading started');
});
// file reading finished successfully
reader.addEventListener('load', function(e) {
// contents of file in variable
var text = e.target.result;
var row = text.split('\n');
row.forEach(function(e) {
var datiGiornalieri = e.split(';');
socket.emit('parameterRegistrationFile', {ID: patientID, paramdata: datiGiornalieri[0], parametername: 'alfa',parametervalue: datiGiornalieri[1] });
});
});
reader.readAsText(file);
});
I have a file upload application which once a file has been selected status will appear saying the name of the file. What I am having an issue with is adjusting the case where there are more than one files being uploaded.
Originally, a count would be given - if you upload three files, '3' would appear. I am attempting to adjust this so that the three file names are displayed. I took the code getting the single file name to show fileName = e.target.value.split('\\').pop(); and tried adding it to the condition is more than one:
if (this.files && this.files.length > 1) {
//fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
//fileName = e.target.value.split('\\').pop();
fileName = e.target.value.split('\\').pop();
console.log('Here is it ' + fileName);
//$('#fileName').html(fileName);
}
What I get is a single file name outputted. I can't figure out how to get the file name list in an array to output.
Does anyone see what I need to adjust?
var inputs = document.querySelectorAll('.inputfile');
Array.prototype.forEach.call(inputs, function(input) {
var label = input.nextElementSibling,
labelVal = label.innerHTML;
if (this.files && this.files.length > 1) {
//fileName = (this.getAttribute('data-multiple-caption') || '').replace('{count}', this.files.length);
//fileName = e.target.value.split('\\').pop();
fileName = e.target.value.split('\\').pop();
console.log('Here is it ' + fileName);
//$('#fileName').html(fileName);
} else {
fileName = e.target.value.split('\\').pop();
console.log("I am running");
}
if (fileName) {
//label.querySelector('span').innerHTML = fileName;
//label.querySelector('span').innerHTML = fileName;
$('#fileName').html(fileName);
$('#fileStatus').text('File attached!');
} else {
label.innerHTML = labelVal;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploadedFile" class="inputfile" id="uploadedFileTest" data-multiple-caption="{count} files selected" multiple>
<label for="uploadedFileTest" id="uploadFileTest"><img class="total-center" src=""></label>
<p id="fileStatus"></p>
<p id="fileName"></p>
I want to change name's file selected by input type=file, but it doesn't work.
This is my code:
$("document").ready(function() {
$('body').on('change', '#FileID', function() {
var name = document.getElementById('FileID');
name.files.item(0).name = Math.floor(Math.random() * 100000);
console.log('Selected file: ' + name.files.item(0).name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='FileID' class='class1' type='file' name='Images' value='' />
To change the name of a File object, you need to create a new File instance.
You can create one from a previous File object and it will act a simple wrapper over the data on disk.
The sketchier part is to update the <input type="file"> value to use this new File.
It is now possible through an hack as exposed in this answer of mine:
$('body').on('change', '#FileID', function(evt) {
const newName = Math.floor(Math.random() * 100000);
const input = evt.currentTarget;
const previousFile = input.files[0];
const newFile = new File([previousFile], newName);
// hack to update the selected file
const dT = new DataTransfer();
dT.items.add(newFile);
input.files = dT.files;
console.log('Selected file: ' + input.files.item(0).name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='FileID' class='class1' type='file' name='Images' value='' />
However since this part is still mainly an hack, I can't really recommend its use.
So if you don't need to show the updated value in the native input, don't do it. Simply update a custom UI, and use a FormData to upload to your server. The last param of FormData#append(blob, fieldname, filename) will set the filename sent by the browser in the form-data request:
const form = new FormData();
const file = new File(["some data"], "originalname.txt");
form.append("fileField", file, Math.floor(Math.random() * 100000));
console.log("original file's name: ", file.name);
new Response(form).text()
.then((content) => console.log("formdata content: ", content));
So you should not need the aforementioned hacks at all.
For anyone ending here trying to get rid of the file's name, try converting it to base64. this way it won't have the name attached to it and you could upload it how you want. I will leave a code example using reactJS for this.
1: Here is the input file type calling the onChange event with our function:
<input onChange={this.handleBackgroundImagePreview} type="file" accept="image/png,image/gif,image/jpeg"></input>
2: Then convert that image to base64
handleBackgroundImagePreview = (e) =>{
// Retrieves the selected Image or file
const file = e.target.files[0]
//Calling async file reader with a callback
let fileBase64 = '';
this.getBase64(file, (result) => {
fileBase64 = result;
console.log(fileBase64)
//In here you could upload to the server the base 64 data as you want
});
}
getBase64(file, cb) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
cb(reader.result)
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
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 <input type="file" id="basicUploadFile" multiple="multiple"> and I want to get all file names inside this input. I've seen some example, but it gets only name of first file.
$ ('#basicUploadFile').live ('change', function () {
alert($ ('#basicUploadFile').val());
});
How can I do this? Thanks.
var files = $('#basicUploadFile').prop("files")
files will be a FileList object.
var names = $.map(files, function(val) { return val.name; });
Now names is an array of strings (file names)
FileAPI reference
files property reference
jsFiddle Demo
You can still access the files as a FileList collection without the need for over-using jQuery. I've created a quick jsFiddle demonstrating how to get the information out of the input using the FileList and File objects. Here is a snippet:
$('#basicUploadFile').live('change', function ()
{
for (var i = 0; i < this.files.length; i++)
{
alert(this.files[i].name);
alert(this.files.item(i).name); // alternatively
}
});
I used this to show in console all files name:
var input_file = $("#input_file");
input_file.on("change", function () {
var files = input_file.prop("files")
var names = $.map(files, function (val) { return val.name; });
$.each(names, function (i, name) {
console.log(name);
});
});
<input name="selectAttachment" id="selectAttachment" type="file" multiple="multiple">
<button class="btn btn-default" onclick="uploadAttachment()" type="submit">Upload</button>
function uploadAttachment() {
debugger;
var files = $('#selectAttachment').prop('files');
var names = $.map(files, function (val) { return val.name; });
}
you can extend the prototype of File Object (for example File.prototype.toJSON), and you can access the FileList of <input ..>:
<input id="myFile" type="file">
var file = document.getElementById('fileItem').files[0];
For more information check this documentation:
https://developer.mozilla.org/en-US/docs/Web/API/FileList#Using_the_file_list
check this simple example:
File.prototype.toJSON = function() {
return {
'lastModified' : this.lastModified,
'lastModifiedDate' : this.lastModifiedDate,
'name' : this.name,
'size' : this.size,
'type' : this.type
};
}
function getFiles() {
var files = document.getElementById('myFiles').files;
document.getElementById('result').innerHTML = '<h1>result</h1>'
+ JSON.stringify(files);
}
<input id="myFiles" type="file" multiple onchange="getFiles()" />
<pre id='result'></pre>
Good Luck!