我有一个react应用程序,用户可以在其中发布带有一些图像的帖子。到目前为止,根据格式的不同,它可以是URL或文件。如果它是一个文件,我想对它进行base64编码,然后向我的服务器发出发布请求。我已经实现了一个功能,并有条件检查它是否是文件
submitPostHandler = (e) => {
e.preventDefault();
const post = {
contents: this.state.content,
images: this.encodeURLHandler(this.state.images)
}
this.setState({ showLoading: true });
PostMapper.submitTextPost(post).then(
this.setState({showLoading: false})
);
}
当我创建一个Post Object时,在此函数的内部,如果有URL,我有一个对base64进行编码的函数
encodeURLHandler = (images) =>{
const expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
const regex = new RegExp(expression);
let urls = [];
images.map(img =>{
if(!img.match(regex)){
urls.push(img);
const reader = new FileReader();
reader.readAsDataURL(urls);
reader.onload = () => {
img = reader.result.replace(/^data:(.*;base64,)?/, '');
if ((img.length % 4) > 0) {
img += '='.repeat(4 - (img.length % 4));
}
}
}
});
}
每当我运行未完成的函数时,都会出现错误:
TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
原因是我在我的子组件中将文件转换为要显示给用户的ObjectUrl,是否有任何办法可以使我的方法产生另一种条件,以便将其转换回文件以显示