How can I read from local file in angularjs without using directive? - angularjs

I have input type="file" and I need to read the event.target.files.
I tried
<input type="file" ng-change="readFile($event)" />
readFile = (e) => {
const file = e.target.files[0];
console.log('file', file);
if (!file) {
return;
}
const reader = new FileReader();
reader.onload = async (evt) => {
const xmlData: string = evt.target.result;
const annotManager = this.wvInstance.annotManager;
const ann = await annotManager.importAnnotations(xmlData);
};
reader.readAsText(file);
}
but in file I don't get File object instnace after the file is selected
I need to get something like this, but I don't get it with this example
How can I do this ?

Related

How do I convert image file to base64?

I am want to save image as base64 to aws s3 bucket. There is a lambda that will decoder the base64.
These are my current states for the images. One is for selected file that is the image and the one is for the image that is seen as preview on the page.
const [selectedFile, setSelectedFile] = useState('')
const [preview, setPreview] = useState()
Then I have useEffect function for selecting the file and also sets the object URL as the preview image.
useEffect(() => {
if (!selectedFile) {
setPreview(undefined)
return
}
const objectURL = window.URL.createObjectURL(selectedFile)
setPreview(objectURL)
return () => window.URL.revokeObjectURL(objectURL)
}, [selectedFile])
const selectFile = (event) => {
setSelectedFile(event.target.files[0])
}
And this is the input component where the onChange function is called.
<Input
style={input}
type='file'
accept='.jpg, .png|image/*'
id='image'
name='Upload image'
onChange={selectFile}
/>
Is there a better way to handle the base64 conversion?
I managed to solve this by relatively short lines of code. I take the selectedFile from the state and then convert it to base64. I tested it with the separate button and I got base64 image in the console.
const convertToBase64 = () => {
const reader = new FileReader()
reader.readAsDataURL(selectedFile)
reader.onload = () => {
console.log('called: ', reader)
setBase64IMG(reader.result)
}
}

How do I retain a file's name when converting to Base64?

I'm using "Input" to get files in a react app. I'm able to get a blob using readAsDataURL() but it's stripping out the file name and is replacing with "Data". When I log the blob I'm getting "data:image/jpeg;base64,/9j/4QAYRXhpZgAAS..." - "data" being the name that displays.
const handleGetFiles = (e) => {
const reader = new FileReader();
reader.readAsDataURL(e);
reader.onload = () => {
fileCollection((fileCollection) => [...fileCollection, {id: index, data: reader.result}]);
}
}
<Input
accept="image/*,video/*"
id="contained-button-file"
multiple type="file"
onChange={e => handleGetFiles(e)}
/>
Is there a way to use URL.createObjectURL(file) instead? I can't get that to work either.
The filename that you're looking for doesn't come from the FileReader API, but rather from the input element's files property.
You can expose the file in 2 ways from React:
Through a ref:
const Input = () => {
const inputEl = React.useRef();
const handleGetFiles = () => {
alert(inputEl.current.files[0].name)
};
return (
<input
...
onChange={handleGetFiles}
ref={inputEl}
/>
);
}
Through the event target
const Input = () => {
const handleGetFiles = (e) => {
alert(e.target.files[0].name)
};
return (
<input
...
onChange={handleGetFiles}
/>
);
}

Read and write in user Uploaded file ReactJS

I have a reactjs application. It is kind of like a text editor. A user can upload files and read/edit the file. So I was able to read the txt file that the user uploads by using this:
displayFile = (i) => {
this.setState({currentFileIndex: i})
const reader = new FileReader();
reader.onload = async (e) => {
const text = e.target.result;
this.setState({fileText: text})
};
reader.readAsText(this.state.files[i].file);
};
onFileSelected = (event) => {
var file = event.target.value;
var startIndex =
file.indexOf("\\") >= 0 ? file.lastIndexOf("\\") : file.lastIndexOf("/");
var filename = file.substring(startIndex);
if (filename.indexOf("\\") === 0 || filename.indexOf("/") === 0) {
filename = filename.substring(1);
}
const filesArray = this.state.files;
filesArray.push({ fileName: filename, file: event.target.files[0] });
this.setState({ files: filesArray });
};
The input html is:
<input
type="file"
accept=".glm, .csv, .player, .txt"
id="Editor_Screen_Upload_Input"
style={{ display: "none" }}
onChange={this.onFileSelected}
/>
So, how can write and save in state if the user edits a file?

How to use FileReader with React? (getting a strange error)

I have tried solutions from
How to use FileReader in React?
and gotten the same error as my code.
I'm trying to use the FileReader() in a react component.
class Home extends Component {
onChange(e) {
let files = e.target.files;
console.log(files);
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = e => {
console.log(e.target.result);
};
}
render() {
return (
<div onSubmit={this.onFormSubmit}>
<h1>Upload File Here</h1>
<input type="file" name="file" onChange={e => this.onChange(e)} />
</div>
export default Home;
console.log(files) returns the uploaded file (if I run it without the rest of the onChange() code). When I run the whole thing, I get an error message of:
Error: cannot read as File: {} on reader.readAsDataURL(files[0]);
I'm following this tutorial exactly and it is working fine for them. Any thoughts?!
https://www.youtube.com/watch?v=sp9r6hSWH_o&t=50s
Try this
Change
onChange(e) {
let files = e.target.files;
console.log(files);
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = e => {
console.log(e.target.result);
};
}
To
onChange = e => {
let files = e.target.files;
console.log(files);
let reader = new FileReader();
reader.onload = r => {
console.log(r.target.result);
};
reader.readAsDataURL(files[0]);
}

Input file(jpg/png) uploading and showing are not working in Reactjs?

File Button is not showing the jpeg image after uploading in locally
Below is the code i have written in react js...
categoryImageArray = [];
getCategoryImageLink = (e) => {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (e) => {
categoryImageArray.push(e.target.result);
}
}
and below is the JSX code
**IMG SRC**
<div>
<img src = { "'" + categoryImageArray[0] + "'" } />
</div>
Input File
<input type="file" onChange = { this.getCategoryImageLink } />
You have to use state for this,set the value of categoryImageArray in state and change it's value in getCategoryImageLink function
Try this.
getCategoryImageLink = (e) => {
let files = e.target.files;
let reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = (e) => {
this.setState({categoryImageArray: ...this.state.categoryImageArray,e.target.result});
}
}

Resources