2.0.0 • Published 3 years ago

m-downloader v2.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

文件下载

  • 安装模块

    npm install m-downloader 或 yarn add m-downloader
  • 引用模块

    import m_downloader from 'm-downloader'
  • 通过代理拦截进行初始化配置

    const handler = {
      construct(target, [url, options] = args) {
        const method = options.method ? options.method.toUpperCase() : 'GET'
        if (method === 'GET') {
          Object.assign(options, { method, url })
        }
        if (method === 'POST') {
          Object.assign(options, {
            url,
            method,
            headers: {
              'Authorization': localStorage.getItem('AUTH_TOKEN')
            }
          })
        }
        return new target(options)
      }
    }
    const Downloader = new Proxy(m_downloader, handler)
    export default Downloader
  • GET请求方式

    const downloader = new Downloader('/api/download', {
      filename: 'Custom file name',
      getProgress(percentage) {
        console.log(`Download progress:${percentage}`)
      }
    })
    downloader
      .catch(error => { console.log(error) })
      .finally(() => console.log('A successful or failed operation, such as the handling of loading'))
  • POST请求方式

    const downloader = new Download('/api/download', {
      method: 'POST',
      data: { id: 5, type: 1 },
    })
    downloader
      .catch(error => { console.log(error) })
      .finally(() => console.log('A successful or failed operation, such as the handling of loading'))
  • 捕获服务端的JSON错误

    {
      "status": 500,
      "msg": "消息提示文案",
    }
    const downloader = new Download('/api/download', {
      method: 'POST',
      data: { id: 5, type: 1 },
    })
    downloader
      .catch(error => {
        console.log('errorMsg', error.statusText)
      })