i have code below in vue js and i wanted to share a file as u can see, but my problem is i want to save that file name that i uploaded to the API json in post method , is there a way to do it and thanks in advance
<div class="input-file">
<input class="input-file__input" ref="file" type="file">
<div class="input-file__button" #click="selectFile()"></div>
</div>
<script>
selectFile(){
let fileInputElement = this.$refs.file;
fileInputElement.click(); //i want to send this file name to api post method
// ...
},
</script>
Assume that you have an input with 'upload' id, then:
log_file_name() {
const path = document.getElementById('upload').value;
if (path) {
let startIndex = (path.indexOf('\\') >= 0 ? path.lastIndexOf('\\') : path.lastIndexOf('/'));
let filename = path.substring(startIndex);
if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
filename = filename.substring(1);
}
console.log(filename);
}
}
<input class="input-file__input" id="upload" #change="log_file_name()" ref="file" type="file">
You can try to subscribe to change event in order to get a selected file:
<input class="input-file__input" ref="file" type="file" #change="changeFile">
changeFile(event) {
const file = event.target.files[0]
}
Related
I created a multiple file upload form. And it shows me the list of files I'm about to upload once I've selected the files. and i made delete file button to remove files that have been deleted from the object but cannot be deleted
<input type="file" class="" id="fileInput" multiple onchange="displayFiles()" style="width: 85px">
function removeFile(index) {
var input = document.getElementById("fileInput");
Array.from(input.files).splice(index, 1);
displayFiles();
}
I tried this method and it didn't work.
function removeFile(index) {
var input = document.getElementById("fileInput");
delete input.files[index];
displayFiles();
}
please help me
Hopefully this small example helps, you could create an array of indices to skip which are used when uploading.
const get = str => document.querySelector(str);
get("#myFiles").addEventListener("change", e => {
get("#howMany").setAttribute("max", e.target.files.length);
});
get("#upload").addEventListener("click", () => {
const files = get("#myFiles").files;
const len = get("#howMany").value;
const data = new FormData();
for (let i = 0; i < len; i++) {
const targetFile = files[i];
data.append("files[]", targetFile, targetFile.name);
}
devFetch("testurl", {
method: "POST",
body: data
});
});
/* DEV FETCH EMULATE NORMAL FETCH FOR STACK SNIPPET, SHOULD JUST BE FETCH */
function devFetch(url, options) {
console.log("Posting to", url, "with method", options.method);
console.log("Body:");
console.log(options.body.getAll("files[]"));
}
<input id="myFiles" type="file" multiple /> <br />
<input id="howMany" type="range" min=0 max=0 /> <br />
<button id="upload">upload</button>
I want to add an image file to "convert" function.
this is my code from the component.html for the input:
<li>
<label for="avatarIMG" id="avatarLbL"> image: </label>
<input type="file" accept="image/*" #imageBox name="image" id="avatarinput" (change)="convert($event)">
<button type="button" id="avatarInputBTN" (click)="imageBox.click()"> Profile Picture </button>
</li>
the event suppose to send the values of the object with all of the values + the image file from the form to the component.ts and this is the code of it:
public convert(e: Event): void {
this.eventFiles = (e.target as HTMLInputElement).files[0];
if (this.eventFiles !== null) {
this.user.image = this.eventFiles;
const fileReader = new FileReader();
fileReader.onload = args => this.preview = args.target?.result?.toString();
fileReader.readAsDataURL(this.eventFiles);
}
}
i get an error of object possibly null for (e.target as HTMLInputElement).files[0].
how can i fix this?..
try this:
this.eventFiles = (e.target as HTMLInputElement)?.files?.[0];
I am trying to get the filepath of the selected file.
Using the debugger, I see that the file has an property called value which is equal to : "C:\fakepath\filename.txt".
However when I try to access file.value, the filepath is equal to null.I am using Java 8, Struts 1.2, Jsps, and Chrome
Javascript:
function validateFile(file)
{
filepath = file.value; /*This is null*/
return true;
}
Html:
<input type="file" id="theFile[0]" onChange="validateFile(this)"/>
Try this:
function validateFile(fileinput) {
var allowed = "pdf,png";
var filepath=fileinput.value;
var ext = filepath.substr(filepath.lastIndexOf('.')+1);
if (filepath = "" || allowed.search(ext) <= -1) {
fileinput.value='';
alert('Invalid file type');
return false;
}
}
<input type="file" id="inputFile" onChange="validateFile(this)"/>
I guess it wasn't too much work after all :)
function validateFile(file)
{
filepath = file.value;
document.getElementById('result').innerText = filepath;
return true;
}
<input type="file" onChange="validateFile(this)"/>
<div id="result">[result will be here]</div>
I actually have a file input and I would like to retrieve the Base64 data of the file.
I tried:
$('input#myInput')[0].files[0]
to retrieve the data. But it only provides the name, the length, the content type but not the data itself.
I actually need these data to send them to Amazon S3
I already test the API and when I send the data through html form with encode type "multipart/form-data" it works.
I use this plugin : http://jasny.github.com/bootstrap/javascript.html#fileupload
And this plugins gives me a preview of the picture and I retrieve data in the src attribute of the image preview. But when I send these data to S3 it does not work. I maybe need to encode the data like "multipart/form-data" but I don't know why.
Is there a way to retrieve these data without using an html form?
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
You can try the FileReader API. Do something like this:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
I created a form data object and appended the file:
var form = new FormData();
form.append("video", $("#fileInput")[0].files[0]);
and i got:
------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv
in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla
Html:
<input type="file" name="input-file" id="input-file">
jQuery:
var fileToUpload = $('#input-file').prop('files')[0];
We want to get first element only, because prop('files') returns array.
input element, of type file
<input id="fileInput" type="file" />
On your input change use the FileReader object and read your input file property:
$('#fileInput').on('change', function () {
var fileReader = new FileReader();
fileReader.onload = function () {
var data = fileReader.result; // data <-- in this var you have the file data in Base64 format
};
fileReader.readAsDataURL($('#fileInput').prop('files')[0]);
});
FileReader will load your file and in fileReader.result you have the file data in Base64 format (also the file content-type (MIME), text/plain, image/jpg, etc)
FileReader API with jQuery, simple example.
( function ( $ ) {
// Add click event handler to button
$( '#load-file' ).click( function () {
if ( ! window.FileReader ) {
return alert( 'FileReader API is not supported by your browser.' );
}
var $i = $( '#file' ), // Put file input ID here
input = $i[0]; // Getting the element from jQuery
if ( input.files && input.files[0] ) {
file = input.files[0]; // The file
fr = new FileReader(); // FileReader instance
fr.onload = function () {
// Do stuff on onload, use fr.result for contents of file
$( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )
};
//fr.readAsText( file );
fr.readAsDataURL( file );
} else {
// Handle errors here
alert( "File not selected or browser incompatible." )
}
} );
} )( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" />
<input type='button' id='load-file' value='Load'>
<div id="file-content"></div>
To read as text... uncomment //fr.readAsText(file); line and comment fr.readAsDataURL(file);
Get file using jquery
element html:
<input id="fileInput" type="file" />
jquery code:
$("#fileInput")[0].files[0]
this work for me :)
HTML
<div class="row form-group my-2">
<div class="col-12">
<div class="">
<div class="text-center">
<label for="inpImage" class="m-2 pointer">
<img src="src/img/no-image.jpg" id="img-visor" height="120" class="rounded mx-auto d-block">
</label>
<input type="file" class="visually-hidden" accept="image/*" name="picture" id="inpImage">
</div>
</div>
</div>
</div>
jQuery
$('#inpImage').change(()=>{
const file = $('#inpImage').prop("files")[0];
const imagen = URL.createObjectURL(file);
console.log(URL.createObjectURL(file));
$('#img-visor').attr('src', imagen);
});
<script src="~/fileupload/fileinput.min.js"></script>
<link href="~/fileupload/fileinput.min.css" rel="stylesheet" />
Download above files named fileinput add the path i your index page.
<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"
`enter code here`accept=".pdf" multiple>
</div>
<script>
$("#uploadFile1").fileinput({
autoReplace: true,
maxFileCount: 5
});
</script>
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('The File APIs are not fully supported in this browser.');
return;
}
var input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
var file = input.files[0];
var fr = new FileReader();
fr.onload = receivedText;
//fr.readAsText(file);
//fr.readAsBinaryString(file); //as bit work with base64 for example upload to server
fr.readAsDataURL(file);
}
}
function receivedText() {
document.getElementById('editor').appendChild(document.createTextNode(fr.result));
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();' />
<div id="editor"></div>
</body>
</html>
I have a part of a form where a user can upload a file. I want only the filename to be sent to a text field in the same form. So if user uploaded "C:/Folder/image.jpg", the text field should show "image.jpg". I tried some code myself but I know it's wrong:
function ff_uploadimages_action(element, action)
{var m = data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/);
switch (action) {
case 'change':
if (data.match(/((*):\/)/(.*)[\/\\]([^\/\\]+\.\w+)$/).value)
ff_getElementByName('filename').value = m[2].text;
default:;
} // switch
} // ff_uploadimages_action
ff_uploadimages is the field to upload file, and filename is the textfield where name should appear. Any help at all is appreciated! Thanks.
Here's one way to do it
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename').value = filename;
}
<input id="upload" type="file" />
<input id="filename" type="text" />
you don't mention jQuery but given it's popularity here's the same solution using jQuery
jQuery:
$('#upload').change(function() {
var filename = $(this).val();
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
$('#filename').val(filename);
});
Demo:
http://jsfiddle.net/pxfunc/WWNnV/4/
HTML:
<input id="upload" type="file" onChange="uploadOnChange(this)" />
<input id="filename" type="text" />
JS:
function uploadOnChange(e) {
var filename = e.value;var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex +1);
}
document.getElementById('filename').value = filename;
}
A shorter way in jQuery would be the following:
HTML
<input type="file" id="inputFile" class="hidden"/>
<input type="text" id="inputDisplayFileName" readonly/>
<button id="buttonChooseFile">Choose file</button>
jQuery
$("#buttonChooseFile").click(funtion()({
$("#inputFile").click();
});
$("#inputFile").change(function(){
var fileName = $("#inputFile").prop('files')[0]["name"];
$("inputDisplayFileName").val(fileName);
});
In this example the default file upload is hidden so that you can style the 'upload file input' as desired. Clicking the button will trigger the original (hidden) file upload. After choosing the file the .onchange() will do the rest of the work, copying the file the 'read only input text'.