如何在浏览器中使用JavaScript获取curl -T --upload-data选项的等效数据格式?

lnlaulya  于 12个月前  发布在  Java
关注(0)|答案(3)|浏览(103)

curl有-T,--upload-file选项来“将指定的本地文件传输到远程URL”。

curl -v "http://some/data/consumer" -XPOST -T "some/file/name"

字符串
如何使用JavaScript从<input type="file" />获取curl -T文件的等效数据?

2j4z5cfb

2j4z5cfb1#

如果你想从JavaScript中访问数据,例如通过数据视图,那么你可以使用Blob.arrayBuffer()方法,它将返回一个解析为ArrayBuffer的Promise。由于 File 接口继承自 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);
};

个字符

  • 请注意,此方法在旧浏览器中可能需要polyfill。*

但是如果你只是想把文件作为二进制文件发送到服务器,那么XHRfetch接受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]);

nbewdwxp

nbewdwxp2#

你应该创建一个FileReader并使用readAsArrayBuffer方法读取文件。

const readBlob = file =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = e => {
      resolve(e.target.result);
    };
    reader.onerror = reject;
    reader.readAsArrayBuffer(file); // THIS
  });

字符串
然后你可以发送请求,比如用axios,像这样。

const blob = await readBlob(...);
axios.post('http://some/data/consumer', blob);

xuo3flqw

xuo3flqw3#

我创建的小脚本,使用Node js:本地上传文件POST请求到REST API en-point:希望它有助于如果有人想上传一个文件“内容类型”:“multipart/form-data”.你需要所需的依赖http或https/request-promise-native/fs:

const https = require('https');
const rq = require('request-promise-native');
const fs = require('fs');

const url = "<API_url>"
const Agent = new https.Agent({ keepAlive: true , maxSockets :3 });
const user_name= "<provide_username>";
const user_password = "<provide_user_password_or_api_key>";
var user_info = btoa(`${user_name}` + ':' + `${user_password}`);   //base64 conversion, user_password can be API key as well.

const request = rq.defaults({
    headers:    
        {                                       
            'Authorization': 'Basic ' + `${user_info}`
        },
    agent: Agent,   
});

const readStream = fs.createReadStream("./test_file.txt"); //read file from local

async function  uploadattachment() {
    try { 
        const vurl = `${url}`
        writeLog(vurl)
        const opt = { 
                    url:vurl,                                           
                    method:"POST",
                    headers:{
                        "Content-Type":"multipart/form-data"
                    },
                    formData : {
                        "attachment" : readStream
                    }
                }
        const responseBody = await request({...opt,         
                });
        const request_response = JSON.parse(responseBody); 
        console.log("upload request Response :", request_response);
        return true;
    } catch(e) {
        console.log(e);
        throw e
    }
}    
uploadattachment();

字符串

相关问题