【问题标题】:Can't preview image while uploading in React在 React 中上传时无法预览图像
【发布时间】:2020-11-16 19:45:55
【问题描述】:

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

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();
} 

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

这种行为有原因吗?

【问题讨论】:

    标签: reactjs fluent


    【解决方案1】:

    您没有更新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
         });
     };
    

    【讨论】:

    • 非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-30
    相关资源
    最近更新 更多