解决img中不能使用绝对

报错原因

如果页面在服务器上,浏览器出于安全考虑是不允许html访问本地文件的。

解决方案

1、设置映射
2、相对路径
3、读取本地文件,然后返回result
4、通过localhost,本地端口,设置动态url

这里我太菜了,只会第三种

第三种解决方案

使用FileReader读取文件,然后将result返回给src。

function previewFile() {
  const img = document.getElementById('img')
  const file = document.getElementById('file').files[0]; // 使用input,type='file'获取本地文件,也可以通过其他方式,比如createReadStream
  const reader = new FileReader()
// 读取指定文件或Blob对象,读取完成触发loadend事件,同时result属性将包含一个data:URL格式的字符串,表示所读取文件的内容
  file && reader.readAsDataURL(file);
  reader.addEventListener("load", function() {
    img.src = reader.result;
  }, false) 
}

第四种解决方案

最近一直看,终于看懂了
大佬主要用到的东西是express和fs。
大概思路

  const exp = require('express')
  const fs = require('fs-extra')
  const path = require('path')

  exp.get('/:taskcode/cover.jpg', (req, res) => {
      const filePath = path.join(getDirpath(taskCode), 'cover.jpg') // 获取本地路径
      try {
           // 同步查看文件权限
           fs.accessSync(filePath, fs.constants.R_OK)
           // 然后将文件数据给res发送出去
           fs.createReadStream(filePath).pipe(res);
      } catch(error) {
        res(error)
      }
  })


// 上面准备工作做完
  <img src=`http://localhost:${port}/${taskCode}/cover.jpg` />

参考文档:
readAsDataURL
FileReader

posted @ 2023-03-15 20:03  卿六  阅读(73)  评论(0编辑  收藏  举报