本文介绍了如何在react中加载图像并转换为blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于React的问题.我有一种方法,单击后即开始导入图像.实际上,我在文件输入中有使用此方法的onChangeevent:
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
};
现在,我必须将此上传的文件转换为Blob.我该怎么办?
Now I have to convert this uploaded file to blob. How can I do this please?
我的其他代码如下:
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>
);
}
}
推荐答案
下面是一个示例,您如何使用 FileReader.readAsDataURL
Here'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>
这篇关于如何在react中加载图像并转换为blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!