最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】ReactJS中如何把input上传的照片显示出缩略图

ReactJS crifan 7241浏览 0评论

折腾:

【记录】尝试去用H5实现弹出选择相机还是相册的方式实现图片文件上传

期间,已经通过:

【已解决】JS中的File对象有哪些属性以及如何获得file的data数据

拿到了file的对象。

现在就是需要去实现,如何将通过input已获得的图片的file:

去显示出来缩略图

刚看到:

Using files from web applications | MDN

好像有参考代码。

Example: Showing thumbnails of user-selected images

react js from file show image thumb

javascript – How to generate a thumbnail image after adding an image inside an input type="file" in a form and submitting them both on the same form – Stack Overflow

【总结】

然后用代码,是可以实现基本的显示缩略图的效果的:

(虽然还有:没有等比例缩放,显示图片后没有去除掉+等小问题)

                    <input
                      id="uploaderCustomInput"
                      class="weui-uploader__input"
                      type="file"
                      accept="image/*"
                      multiple=""
                      onChange={this.handleFileChange}
                    >
                    </input>
                      <img
                        ref={(imgCowLeft) => {this.imgCowLeft = imgCowLeft;}}
                        src=""
                        width="77"
                        height="77"
                      />
  handleFileChange(e) {
    console.log(`handleFileChange:`);
    console.log(e);
    console.log(e.target);
    console.log(e.target.files);
    if (e.target.files.length > 0) {
      let curFile = e.target.files[0];
      weui.alert(`File info: name=${curFile.name}, size=${curFile.size}, webkitRelativePath=${curFile.webkitRelativePath}, lastModifiedDate=${curFile.lastModifiedDate}, lastModified=${curFile.lastModified}`);
      console.log(this.imgCowLeft);
      let reader = new FileReader();
      console.log(this.reader);
      reader.onloadend = () => {
        console.log("reader.onloadend:");
        // console.log(reader.result); //data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAA
        this.imgCowLeft.src = reader.result;
      };
      if (curFile) {
        console.log("before reader.readAsDataURL");
        reader.readAsDataURL(curFile);
      } else {
        this.imgCowLeft.src = "";
      }
    }
  }

iPhone6中的实际的效果是:

转载请注明:在路上 » 【已解决】ReactJS中如何把input上传的照片显示出缩略图

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.168 seconds, using 22.14MB memory