1

我有这个 curl 请求工作。

curl -v "https://developer.api.autodesk.com/oss/v2/buckets/:bucketName/objects/" 
-X "PUT" -H "Authorization: Bearer tokenGoesHere" 
-H "Content-Type: application/octet-stream" -T "forupload.rvt"

如何使用 npm 请求模块在节点中编写此内容。我用'request'和'fs'尝试了以下内容。我回来了“请求中没有提供令牌”。

    function uploadFile(bucketData){
        var uri = 'https://developer.api.autodesk.com/oss/v2/buckets/' + bucketData['bucketKey'] + '/objects/'
        var authorizationHeader = ' Bearer ' + bucketData['token'] // this works in other post/get requests
        var contentTypeHeader = 'application/octet-stream'
        var streamTarget = 'C:\\Users\\architech\\Desktop\\Forge Node\\Test.rvt';
        console.log(uri)
        console.log(authorizationHeader)
        console.log(contentTypeHeader)
        console.log(streamTarget)
// console output:
// https://developer.api.autodesk.com/oss/v2/buckets/bucketpqglrzt/objects/
// Bearer ....token....
// application/octet-stream
// C:\Users\architech\Desktop\Forge Node\Test.rvt

        request.put(
            {
                url: uri,
       //       preambleCRLF: true,
       //       postambleCRLF: true,    
                multipart: 
                [
                    {
                        'Authorization': authorizationHeader,
                        'Content-Type': contentTypeHeader,                   
                         body: fs.createReadStream(streamTarget)
                    },  
                ]         
            },

            function(error, response, body){ 
                if(!error){
                    console.log(body);
                }else{
                    console.log(error);
                }
            })
    }
4

1 回答 1

2

在尝试了几种方法之后,虽然我无法重现您的具体问题,但我遇到的问题是二进制附件正确加载。因为createReadStream()异步运行,它似乎并没有像请求文档所说的那样在添加到multipartorformData键时真正起作用。不知道这是为什么?

我首先使用http://requestb.in让它工作- 将 curl 请求与使用 Node.js 构造的相同请求进行比较。这是最终的工作版本:

var request = require('request')
fs = require('fs')

var options = {
    uri: 'https://developer.api.autodesk.com/oss/v2/buckets/<yourBucket>/objects/<yourFile.ext>',
    headers: {
        'Content-Type': 'application/octet-stream',
        'Authorization': 'Bearer <token>'
    }
}

fs.createReadStream(__dirname + '/<fileName.ext>').pipe(request.put(options, function(err, response, body) {
    console.log(body)
    /*
        {
          "bucketKey" : "< yourBucket>",
          "objectId" : "urn:adsk.objects:os.object:brandontestbucket2/skyscpr1.3ds",
          "objectKey" : "<fileName.ext>",
          "sha1" : "...redacted...",
          "size" : 43791,
          "contentType" : "application/octet-stream",
          "location" : "https://developer.api.autodesk.com/oss/v2/buckets/< yourBucket>/objects/<fileName.ext>"
        }
    */
}))
于 2017-01-25T05:49:54.620 回答