美文网首页
2019-07-19 File API常用操作

2019-07-19 File API常用操作

作者: __唐一__ | 来源:发表于2019-07-19 14:03 被阅读0次

应用场景

用户头像上传和预览,用户选择图片后,立即展示供预览,但是真正提交时才上传

本地读取方式有两种方式(也许还有更多,这里说两种).

1.读取到JavaScript中

  function readImg(file, targetImg) {
    let fr = new FileReader();
    fr.onload = function(e) {
      targetImg.src = fr.result;
    };
    fr.onerror = function(e) {
      console.error('读取失败');
    };
    fr.readAsDataURL(file);
  };
  

2.直接使用文件内容

  function readImg(file, targetImg) {
    targetImg.src = URL.createObjectURL(file);
  };
  

相关文章

网友评论

      本文标题:2019-07-19 File API常用操作

      本文链接:https://www.haomeiwen.com/subject/rjnjlctx.html