curl 有-T, --upload-file选项“将指定的本地文件传输到远程 URL”。
curl -v "http://some/data/consumer" -XPOST -T "some/file/name"
如何使用 curl -T
获取文件的等效数据,来自<input type="file" />
使用 JavaScript?
最佳答案
如果您想要从 javascript 访问数据,例如通过数据 View ,那么您可以使用 Blob.arrayBuffer()
方法,它将返回一个解析为 ArrayBuffer 的 Promise。由于File接口(interface)继承自Blob,因此该方法也可以直接在File对象上使用。
document.getElementById('inp').onchange = async function(evt) {
const buf = await this.files[0].arrayBuffer();
console.log( buf.byteLength );
const view = new Uint8Array(buf, 0, 4); // create a view of 4 first bytes
console.log(view);
};
<input type="file" id="inp">
请注意,此方法可能需要在旧版浏览器中使用polyfill。
<小时/>但是,如果您只是希望将该文件作为二进制文件发送到服务器,则 XHR
和 fetch
接受 Blob 作为请求正文:
// using XHR
const xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.send(input.files[0]);
// using fetch
fetch(url, { method: "POST", body: inp.files[0] } );
// using axios
axios.post(url, inp.files[0]);
关于javascript - 如何在浏览器中使用JavaScript从<input type ="file"/>获取curl -T --upload-data选项的等效数据格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59836220/