OneDrive API Node.js - Can´t use :/createUploadSession Content-Range Error

前端 未结 2 533
孤独总比滥情好
孤独总比滥情好 2021-01-16 08:43

My problem was that I couldn´t upload files bigger than 4MB so I used the createuploadsession according to createuploadsession

I successfully get the uploadUrl value

2条回答
  •  無奈伤痛
    2021-01-16 09:24

    This is the ES6 version of Tanaike's solution.

    const fs        = require('fs')
    const promisify = require('promisify')
    const readFile  = promisify(fs.readFile)
    
    
    const uploader = async function(messageId) {
      // const client = 
    
      const address = '/path/to/file_name.jpg'
      const name    = 'file_name.jpg'
    
      const stats = fs.statSync(address)
      const size  = stats['size']
    
      const uploadSession = { AttachmentItem: { attachmentType: 'file', name, size } }
    
      let location = ''
    
      function getparams() {
        const chSize = 10
        const mega   = 1024 * 1024
    
        const sep = size < (chSize * mega) ? size : (chSize * mega) - 1
        const arr = []
    
        for (let i = 0; i < size; i += sep) {
          const bstart = i
          const bend   = ((i + sep - 1) < size) ? (i + sep - 1) : (size - 1)
          const cr     = 'bytes ' + bstart + '-' + bend + '/' + size
          const clen   = (bend != (size - 1)) ? sep : (size - i)
          const stime  = size < (chSize * mega) ? 5000 : 10000
    
          arr.push({ bstart, bend, cr, clen, stime })
        }
    
        return arr
      }
    
      async function uploadFile(url) {
        const params = getparams()
    
        for await (const record of params) {      
          const file = await readFile(address)
    
          const result = await request({
            url,
            method: 'PUT',
            headers: {
              'Content-Length': record.clen,
              'Content-Range': record.cr,
            },
            body: file.slice(record.bstart, record.bend + 1),
            resolveWithFullResponse: true
          })
    
          location = (result.headers && result.headers.location) ? result.headers.location : null
          // await new Promise(r => setTimeout(r, record.stime)) // If you need to add delay
        }
      }
    
      const result = await client.api(`/me/messages/${messageId}/attachments/createUploadSession`).version('beta').post(uploadSession)
    
      try {
        await uploadFile(result.uploadUrl)
      } catch (ex) {
        console.log('ex.error:', ex.error)
        console.log('ex.statusCode:', ex.statusCode)
        await request.delete(result.uploadUrl)
      }
    
      return location
    }
    

提交回复
热议问题