The front end obtains the File object through the URL (ready-made code)

你越是认真生活,你的生活就会越美好!

introduce

Because there are many types of excel forms in the company's projects, the gap between different forms is relatively large, and it is difficult to develop reusable components at the front end, so it was recently introduced to process Excel forms, support direct import of SpreadJSexcel files, and generate similar excel files in the page The function of the table supports editing, exporting excel, generating json and other functions, so that related page functions do not require front-end development, and achieve the role of open source (ape) throttling

New data can be processed directly by uploading an excel file, however 旧数据只有excel的 url 地址,没有 File 格式的内容, it is necessary to obtain the File method through the URL, the code is as follows (can be directly copied and used)

async function getFile(url, fileName) {
    
    
// 通过 url 获取到 File
  function getFileFromUrl(url, fileName) {
    
    
    return new Promise((resolve, reject) => {
    
    
      let blob = null
      let xhr = new XMLHttpRequest()
      xhr.open('GET', url)
      // 这里设置接收的响应体类型(试了不设置也正常)
      xhr.setRequestHeader('Accept', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
      xhr.responseType = 'blob'
      // 加载时处理(异步)
      xhr.onload = () => {
    
    
        // 获取返回结果
        blob = xhr.response
        console.log('blob:', blob)
        let file = new File([blob], fileName, {
    
     type: blob.type })
        // 返回结果
        resolve(file)
      }
      xhr.onerror = (e) => {
    
    
        reject(e)
      }
      // 发送
      xhr.send()
    })
  }
  const file = await getFileFromUrl(url, fileName)
  console.log('file:', file)
}
// 这个地址没有跨域问题 https://img2.baidu.com/it/u=2149607209,2234358780&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=255  
let url1 = 'https://bargaining.oss-cn-shenzhen.aliyuncs.com/upload/2020/9/15/1600153305138.xlsx?Expires=4753753305&OSSAccessKeyId=LTAIHonqvbarNqaq&Signature=f%2Fstpo0rlI2TUkbGiNZzo6fT%2Fto%3D'
const fileName = '文件名称'
getFile(url1, fileName)

If you encounter the following 跨域报错, you need to find the domain name of the operation and maintenance file address to configure cross-domain. For details, you can read 15 beautiful animations to fully explain CORS (cross-domain resource sharing, same-origin policy)

Access to XMLHttpRequest at 'https://bargaining.oss-cn-shenzhen.aliyuncs.com/upload/2020/9/15/1600153305138.xlsx?Expires=4753753305&OSSAccessKeyId=LTAIHonqvbarNqaq&Signature=f%2Fstpo0rlI2TUkbGiNZzo6fT%2Fto%3D' from origin 'https://editor.csdn.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

insert image description here
Configure cross-domain as shown below
insert image description here

After the cross-domain is configured, the following print information will be obtained after execution
insert image description here

If you encounter the following error, it means that the current access address is httpsa protocol, and the requested url address is httpa protocol , you need to change the requested address to httpsa protocol, or directly remove urlthe protocol prefix of the address, which will automatically match

If the current access address is httpa protocol, the requested urladdress is httpa protocol or httpsthe protocol can be requested normally

index.js:375 Mixed Content: The page at 'https://skyeye-admin.aupup.com/enterprise-info' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://img2.baidu.com/it/u=2149607209,2234358780&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=255'. This request has been blocked; the content must be served over HTTPS.

insert image description here

get file type

Here is a way to get the file type, you need to download the file to the local first, and then upload it manually

const input = document.createElement('input')
input.setAttribute('type', 'file')
document.body.appendChild(input)
input.addEventListener('change', (e)=> {
    
    
    console.log(e.target)
    console.log(e.target.files[0])
    console.log(e.target.files[0].type)
})
input.click()
// 上传本地文件后 可以查看对应的 File ,里面的 type 就是文件类

insert image description here

recommended reading

Vue source code learning directory

Vue source code learning complete directory

Connect the dots - the road to front-end growth

Connect the dots - the road to front-end growth


谢谢你阅读到了最后~
期待你关注、收藏、评论、点赞~
让我们一起 变得更强

Guess you like

Origin blog.csdn.net/weixin_42752574/article/details/125979121