在 React 中上传时无法预览图像

Can't preview image while uploading in React

我阅读了关于这个主题的多篇文章,但仍然无法完成。我正在尝试在上传图像时预览图像

interface IInternalContactsContainerState {
    isModalOpen?: boolean;
    rows: {}[];
    pictures: {}[];
    file: Blob[];
    imagePreviewUrl: string;
    imagePreview: object;
    images: string;
    setImages: string;
    imgSrc: string;
}

constructor() {
    super({});

    this.state = {
        isModalOpen: false,
        rows: [{}],
        pictures: [],
        file: [],
        imagePreviewUrl: "",
        imagePreview: null,
        images: "",
        setImages: "",
        imgSrc: ""
    };
}
<img src={this.state.imagePreviewUrl} /> // in constructor don't initilazie with array instaed with blank string
<input id="new_post_image" className="file-image" type="file" name="image" accept="image/*" onChange={this.imageChange.bind(this)} ref={(input) => {this.state.pictures[0] = input}} />
<button type="button" className="camera-button" onClick={this.fileUpload.bind(this)}>
    <i className="fas fa-camera"></i>
    <label className="camera-text"><h4 className="camera-text">Image</h4></label>
</button>

private imageChange(e) {
e.preventDefault(); 
let reader = new FileReader();
let file = e.target.files[0];

reader.onloadend = () => {
    this.setState({
    file: file,
    imagePreviewUrl: "" //| ArrayBuffer
    });
}

reader.readAsDataURL(file)
}

fileUpload() {
$("#new_post_image").click();
} 

但是,当我尝试上传时,我没有得到图像,而是得到带有图像名称的字符串

这种行为有原因吗?

您没有更新 imagePreviewUrl

试试这个:

reader.onload = function (event) {
    // Add the file name to the data URL
    let dataURL = event.target.result;
    dataURL = dataURL.replace(";base64", `;name=${file.name};base64`);
    this.setState({
        file: file,
        imagePreviewUrl: dataURL
     });
 };