2017-07-18 78 views
0

因此,我可以将图像转换为base64,然后POST使用JSON,这是方便的,像这样的图像数据:用的Node.js和浏览器,HTTP POST原始二进制数据,而无需使用形状数据

curl -u "username:pwd" \ 
    -X PUT \ 
    -H "Content-Type: application/json" \ 
    -d '{"image":"my-base64-str-data"}' \ 
    http://maven.nabisco.com/artifactory/cdt-repo/folder/unique-image-id 

但是,我的问题是 - 有没有办法发送原始的二进制图像数据,而不是编码为base64?用cURL或Node.js怎么能做到这一点?是否可以发送文件或二进制数据而不使用HTTP请求中的表单数据?

但是,在一天结束时,我想从浏览器发布图像,在这种情况下,将图像编码为base64可能是唯一的方法吗?

+0

[JSON字符串中的二进制数据可能重复。比Base64更好的东西](https://stackoverflow.com/questions/1443158/binary-data-in-json-string-something-better-than-base64)。查看@Ælex的答案。 – cybersam

+0

不,我不想把二进制数据放在JSON中,我正在寻找在请求中写入二进制文件,并完全避免JSON –

回答

1

卷曲

正如你可以在curl manpage阅读,这种形式上传通过指定的数据串完成的,可以直接从一个文件--data-binary @/path/to/file语法完成:

--data-binary <data> 
      (HTTP) This posts data exactly as specified with no extra processing whatsoever. 

      If you start the data with the letter @, the rest should be a filename. Data is 
      posted in a similar manner as --data-ascii does, except that newlines and car‐ 
      riage returns are preserved and conversions are never done. 

      If this option is used several times, the ones following the first will append 
      data as described in -d, --data. 

如果图像只能以您的语言中的二进制字符串形式提供,例如作为Node.js缓冲区,并且您不希望击中文件系统,那么您可能必须通过将其包含在'字符中并将其替换为每个'字符与适当的转义序列的字符串如'\''或如果这让你不安,'"'"'。 (回想一下,echo 'abc'"def"'ghi'回音必abcdefghi为一个单元。)

Node.js的

节点是多一点宽容,因为它有一个明确的缓冲类型,但它确实需要多一点建设,使其工作。在这里,我将回复数据封装在Promise中以备需要时使用:

const http = require("http"); 
function upload(image_buffer, image_id) { 
    return new Promise((accept, reject) => { 
    let options = { 
     method: "PUT", 
     hostname: "maven.nabisco.com", 
     port: 80, 
     path: "/artifactory/cdt-repo/folder/" + image_id, 
     headers: { 
     "Content-Type": "application/octet-stream", 
     "Content-Length": image_buffer.length 
     } 
    }; 
    let data = []; 
    let request = http.request(options, response => { 
     response.on("data", chunk => data.push(chunk)); 
     response.on("end",() => 
     accept({ 
      headers: response.headers, 
      statusCode: response.statusCode, 
      data: Buffer.concat(data) 
     }) 
    ); 
    }); 
    request.on("error", err => reject(err)); 

    request.write(image_buffer); 
    request.end(); 
    }); 
} 
+0

真棒我会尝试 - 任何想法如何从浏览器发送二进制数据到服务器,没有使用表单数据?这是我最大的问题 - 到目前为止,我只能使用带有base64字符串的表单数据,但我宁愿将图像作为原始二进制文件从浏览器发送到Artifactory。 –

+0

是啊,使用 - 数据二进制工作 - 但就像我说的,我想找到一种方法发送二进制数据从浏览器到服务器。 –

+1

@AlexanderMills尝试[MDN - Web APIs - XMLHttpRequest - 发送和接收二进制数据](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data)。 –

相关问题