Hi I have an issue with react. I have a method which after click is starting to import image. Actualy I have onChangeevent with this method on my file input:
fileUploadInputChange(e) {
console.log(e.target.value); // return url of image like C:\fakepath\pokemon-pikachu-wall-decal.jpg
};
Now I have to convert this uploaded file to blob. How can I do this please?
My other code looks like this:
export class GeneralySettings extends Component {
/**
* PropTypes fot component
* @return {object}
*/
static get propTypes() {
return {
userData: PropTypes.object.isRequired,
};
};
constructor(props) {
super(props);
this.state = {
showAvatarChangeButton: false,
uploadedImage : '',
};
this.inputReference = React.createRef();
}
fileUploadAction(){
this.inputReference.current.click();
};
fileUploadInputChange(e){
console.log(e.target.value);
};
/**
* Render method for user profile
* @return {*}
*/
render() {
return (
<div className={'d-flex flex-column mr-2'}>
<div className={'position-relative'}
onMouseEnter={() => this.setState({showAvatarChangeButton: true})}
onMouseLeave={() => this.setState({showAvatarChangeButton: false})}>
<Avatar name="Foo Bar" className={'position-relative button-cursor'}/>
<div
className={`position-absolute ${(this.state.showAvatarChangeButton ? 'd-inlene-block' : 'd-none')}`}
id={'changeAvatarButton'}>
<Button variant={'dark'} size={'sm'} block
onClick={this.fileUploadAction.bind(this)}> Zmeniť</Button>
<input type="file" hidden ref={this.inputReference}
onChange={(e) => this.fileUploadInputChange(e)}/>
</div>
</div>
);
}
}
Hi I have an issue with react. I have a method which after click is starting to import image. Actualy I have onChangeevent with this method on my file input:
fileUploadInputChange(e) {
console.log(e.target.value); // return url of image like C:\fakepath\pokemon-pikachu-wall-decal.jpg
};
Now I have to convert this uploaded file to blob. How can I do this please?
My other code looks like this:
export class GeneralySettings extends Component {
/**
* PropTypes fot component
* @return {object}
*/
static get propTypes() {
return {
userData: PropTypes.object.isRequired,
};
};
constructor(props) {
super(props);
this.state = {
showAvatarChangeButton: false,
uploadedImage : '',
};
this.inputReference = React.createRef();
}
fileUploadAction(){
this.inputReference.current.click();
};
fileUploadInputChange(e){
console.log(e.target.value);
};
/**
* Render method for user profile
* @return {*}
*/
render() {
return (
<div className={'d-flex flex-column mr-2'}>
<div className={'position-relative'}
onMouseEnter={() => this.setState({showAvatarChangeButton: true})}
onMouseLeave={() => this.setState({showAvatarChangeButton: false})}>
<Avatar name="Foo Bar" className={'position-relative button-cursor'}/>
<div
className={`position-absolute ${(this.state.showAvatarChangeButton ? 'd-inlene-block' : 'd-none')}`}
id={'changeAvatarButton'}>
<Button variant={'dark'} size={'sm'} block
onClick={this.fileUploadAction.bind(this)}> Zmeniť</Button>
<input type="file" hidden ref={this.inputReference}
onChange={(e) => this.fileUploadInputChange(e)}/>
</div>
</div>
);
}
}
Share
Improve this question
edited May 24, 2020 at 12:25
s0xzwasd
3,2243 gold badges19 silver badges29 bronze badges
asked May 24, 2020 at 12:17
Young L.Young L.
1,0424 gold badges18 silver badges37 bronze badges
4 Answers
Reset to default 11Here's an example how can you use FileReader.readAsDataURL
const {useState} = React;
const fileToDataUri = (file) => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event.target.result)
};
reader.readAsDataURL(file);
})
const App = () => {
const [dataUri, setDataUri] = useState('')
const onChange = (file) => {
if(!file) {
setDataUri('');
return;
}
fileToDataUri(file)
.then(dataUri => {
setDataUri(dataUri)
})
}
return <div>
<img width="200" height="200" src={dataUri} alt="avatar"/>
<input type="file" onChange={(event) => onChange(event.target.files[0] || null)} />
</div>
}
ReactDOM.render(
<App/>,
document.getElementById('root')
);
<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
Use FileReader
fileUploadInputChange(e) {
let reader = new FileReader();
reader.onload = function(e) {
this.setState({uploadedImage: e.target.result});
};
reader.readAsDataURL(event.target.files[0]);
}
To show/preview image:
<Avatar src={this.state.uploadedImage} name="Foo Bar" className={'position-relative button-cursor'}/>
// or .. for image , use below
<img src={this.state.uploadedImage} alt={""} />
function dataURItoBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab]);
return bb;
}
Select file Method -
selectFile = () => {
let uploadfile = document.getElementById('upload_doc');
if (uploadfile) {
this.setState({
selectedUploadFile: uploadfile.files[0],
});
}
};
Upload file and sent as form Data -
const formData = new FormData();
formData.append('file', this.state.selectedFile);
this.uploadFile(formData); // here you can use fetch/Axios to send the form data