How to get the file contents using input file in react - javascript

Using file upload i tried to get the json data.
File upload code :
<input
accept=".json"
id="contained-button-file"
multiple
type="file"
onChange={ (e) => this.handleChange(e.target.files) }
/>
<label htmlFor="contained-button-file">
<Button variant="contained" color="primary" component="span">
Upload
</Button>
</label>
handle change function
handleChange(selectorFiles: FileList)
{
const fileReader = new FileReader();
fileReader.readAsDataURL(selectorFiles[0]);
fileReader.onload = (e) => {
var finResult = e.target.result ;
};
}
but i am getting data:application/json;base64,blob in console. instead of getting the json output.

You are using readAsDataURL to read the file, which gives you a data URL (data:application/json etc)
Try using readAsText instead: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsText`
handleChange(selectorFiles: FileList) {
const fileReader = new FileReader();
fileReader.readAsText(selectorFiles[0]);
fileReader.onload = (e) => {
const contents = e.target.result;
console.log(contents);
};
}
You can also use the newer File.text() as well
selectorFiles[0].text().then(contents => {
// do something with the contents of the file
});

Related

Is it possible to display an image that has been selected by an input element?

I wish to display an input element's selected image. Can this be performed on a local file, accessing the image client side, or would I need to upload the image to a server?
Here's my attempt in React. I can access the correct file name from the input element using inputElem.files[0].name. As soon as I am trying to set an image element to it, the broken image icon is displayed, and no error is surfaced.
const App = () => {
// state to keep track of img elements src. The default works fine.
const [imgSrc, setImgSrc] = useState('/images/test.jpg')
function handleImgUpload() {
const url = '/images/' + e.target.files[0].name
setImgSrc(url)
console.log(url) // /images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG
}
function handleImgLoadSuccess() {
console.log('image loaded!')
}
function handleImgLoadError() {
console.log('image not loaded')
}
return (
<div>
<div>
<label htmlFor="img">Select an image:</label>
<input
type="file"
id="img"
name="img"
accept="image/png, image/jpeg"
onChange={(e) => handleImgUpload(e)}
/>
</div>
<img
src={imgSrc}
alt="Your upload"
onLoad={handleImgLoadSuccess}
onError={handleImgLoadError}
/>
</div>
)
}
In the console, however, the url seems to be correct.
<img src="/images/26e3e793-98f5-4720-9f82-8963276d5e27.JPG" height="100" width="200" alt="Input" class="jsx-855240488">
Hey – I see what you're trying to do, but it doesn't look like this will work. You need to create a new file reader.
const showTempImage = (e) => {
const file = e.target.files[0];
const img = document.createElement("img");
const reader = new FileReader();
reader.addEventListener('load', (e) => {
img.src = e.target.result;
});
reader.readAsDataURL(file);
// Append the img tag to the dom somewhere
}
This did the trick by creating a correct blob url.
const inputImg = e.target.files[0]
const url = URL.createObjectURL(inputImg)
// blob:http://localhost:3000/test-img.jpg
The resulting file stays in memory and needs to be removed in order to create memory leaks.
URL.revokeObjectURL(url)
This also seems to be accomplishable with FileReader, though there are differences.

how can i read with jquery a file csv that has been uploaded with html form?

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);
});

Image preview before upload in angular 5

I have this code to show the image preview before uploading it. However I am working with Angular 5 so I have a .ts file instead of a .js one. How can I do the same in Angular 5? I also want to show the image in all browsers.
My HTML:
<input type='file' onchange="readURL(this);"/>
<img id="blah" src="http://placehold.it/180" alt="your image"/>
My CSS:
img {
max-width:180px;
}
input[type=file] {
padding: 10px;
background: #2d2d2d;
}
My JavaScript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementById('blah').src=e.target.result
};
reader.readAsDataURL(input.files[0]);
}
}
.html
Update event attr and handler param for input.
And you should use data binding for src attribute. Following will apply src if it's not null or undefined or hardcoded url ('http://placehold.it/180')
<input type='file' (change)="readURL($event);" />
<img id="blah" [src]="imageSrc || 'http://placehold.it/180'" alt="your image" />
.ts
In component ts file (class) you should have property imageSrc which be used in view (html) and your function should be a method of that class
...
imageSrc: string;
...
constructor(...) {...}
...
readURL(event: Event): void {
if (event.target.files && event.target.files[0]) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = e => this.imageSrc = reader.result;
reader.readAsDataURL(file);
}
}
I know I'm late but just ran into this problem for both image and audio. The above solutions worked just fine for images but not so well for audio. I eventually got it all working by using a URL object instead of FileReader object that everyone is using.
something like the following
component.ts file ~
imgSrc = 'assets/path/to/default/image.jpeg'
imgFileSelected(event: any) {
if (event.target.files && event.target.files[0]) {
this.imgSrc = URL.createObjectURL(event.target.files[0]);
}
}
My component.html looks like~
<img [src]="imgSrc | sanitizeUrl"> <!-- using a Custom Pipe -->
Finally I created a custom pipe to rid the console of warnings.
my pipe is as follows~
#Pipe({
name: 'sanitizerUrl'
})
export class SanitizerUrlPipe implements PipeTransform {
constructor (
private sanitize: DomSanitizer
) {}
transform(value: string): SafeUrl {
return this.sanitize.bypassSecurityTrustUrl(value);
}
}
To see how I used this for the audio tag you can check out this link. It's only 2 extra lines of self-explanatory code.
I am using the below code to implement the image preview:
onFileChange(event: any) {
this.userFile = event.target.files[0];
this.imageSelected = this.userFile.name;
if (event.target.files && event.target.files[0]) {
const reader = new FileReader();
reader.onload = (e: any) => {
this.imageSrc = e.target.result;
};
reader.readAsDataURL(event.target.files[0]);
}}
Which works just fine and displays the image preview. The problem I originally faced was that I receeived the below error in the chrome developer tools each time an image preview is generated:
Everything worked fine though, there are no other errors.
If I clicked on the null:1 I was directed to the below:
After some fiddling and troubleshooting, I was able to find the solution which I have included in the edit below.
EDIT: Figured it out. I didn't have the || 'http://placehold.it/180'" included in the [src]=" on my component.html. Guess its a timing issue. Sorted now. no more error.
What about using #HostListner, since Angular doesn’t come with a built-in value accessor for file input.
#HostListener('change', ['$event.target.files'])
emitFiles( event: FileList ) {
const file = event && event.item(0);
this.onChange(file);
const reader = new FileReader();
reader.readAsDataURL(file); // toBase64
reader.onload = () => {
this.imageURL = reader.result as string; // base64 Image src
};
Then in the HTML, you may use something like:
<picture >
<source media='(min-width:0px)' [srcset]="imageURL">
<img src="" [alt]="Your photo">
</picture>
Kindly change like --> this.url = event.target.result;
readURL(event:any) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event:any) = > {
this.url = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
}
You might just need to change your javascript function to typescript as below.
readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = (e:any) => {
(<HTMLImageElement>document.getElementById('blah')).src=e.target.result
//assuming element with id blah will always be an ImageElement
};
reader.readAsDataURL(input.files[0]);
}
}
That should be it.
Update
You can also define a property and bind it to image src and change its value accordingly as below:
In your .ts file before constructor, define a property as url and set its default value to http://placehold.it/180.
url: string = 'http://placehold.it/180';
You can update this property within reader.onload as below:
readURL(event:any) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event:any) => {
this.url = event.target.result;
}
reader.readAsDataURL(event.target.files[0]);
}
}
Your html will now look like below:
<input type='file' (change)="readURL(this);" />
<img id="blah" [src]="url" alt="your image" />
to preview the chosen image before uploading this code will help you it,s easy. it,s preview only image if anything else then it,s will give you error
this code is for component.ts
public imagePath;
imgURL: any;
public message: string;
preview(files) {
if (files.length === 0)
return;
var mimeType = files[0].type;
if (mimeType.match(/image\/*/) == null) {
this.message = "Only images are supported.";
return;
}
var reader = new FileReader();
this.imagePath = files;
reader.readAsDataURL(files[0]);
reader.onload = (_event) => {
this.imgURL = reader.result;
}
}
and these lines of code in component view
<span style="color:red;" *ngIf="message">{{message}}</span>
<input #file type="file" accept='image/*' (change)="preview(file.files)" />
<img [src]="imgURL" height="200" *ngIf="imgURL">
First we input the image by upload in choose file (imagedisplay.component.html) :
<input #Image type="file" (change)="handleFileInput($event.target.files)"/>
<img width="100%" *ngIf="imageUrl" [src]="imageUrl" class="image">
Then we use the function for reading and displaying further this is done so (imagedisplay.component.ts):
export class ImageDisplayComponent {
name = 'Angular';
fileToUpload: any;
imageUrl: any;
handleFileInput(file: FileList) {
this.fileToUpload = file.item(0);
//Show image preview
let reader = new FileReader();
reader.onload = (event: any) => {
this.imageUrl = event.target.result;
}
reader.readAsDataURL(this.fileToUpload);
}
}
For those who followed the accepted answer and had type 'string | ArrayBuffer' is not assignable to type 'string'; you need to add as string when affecting render result to your image src as the following
readURL(event: Event): void {
...
reader.onload = e => this.imageSrc = reader.result as string;
...
}
}

Change name File selected by input type file

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);
};
}

Insert a photo to <img> by opening <input type = "file">

Tell me, please, how can a photo be inserted to <img>, when I open
<input type = "file"> and choose any file ?
How can I use JS / JQuery ?
Use 'FileReader' object:
$("#yourinput").change(function () {
var file = this.files[0];
var reader = new FileReader();
reader.onload = function (e) {
$("#yourimg").attr("src", e.target.result);
}
reader.readAsDataURL(file);
});

Categories