相当于 fs.readFile() -> 到 -> DOM 中的 HTML 上传



我试图通过对一些现有js进行改造来将二进制文件发送到API。

现有的和我的之间的巨大差异:

使用Node导入二进制文件并发送到API(我需要什么(

从浏览器上传二进制文件/html并发送到API(现有(

事实证明,我使用fs.readFile((的努力是失败的。在检查现有脚本(下面的链接(时,文件在发送到API之前没有发生任何特殊情况。。。

您可以在此处查看正在运行的现有代码/脚本:https://api.pvpgn.pro/example/d2edit/https://github.com/pvpgn/api.pvpgn.pro/blob/master/WebAPI/wwwroot/example/d2edit/index.html

// Main culprit///
async function readSave() {
fs.readFile('asdgasdgasdg.d2s', async function read(err, data) {
if (err)
throw err;
if (data){
uploadFile(data, 'charinfo')
}
})
}
//// CODE BELOW WORKS WITH FILE UPLOAD FROM WEBPAGE /////
function uploadFile(file, type) {
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open('POST', url, true);
xhr.addEventListener('readystatechange',
function (e) {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
// Done. Inform the user
var json = JSON.parse(xhr.responseText);
console.log(json);
if (json.result === "error") {
if (type === 'charinfo') {
// try the same file with charsave type
uploadFile(file, 'charsave');
} else {
return throwError(json.errorMessage);
}
} else {
charObjects.push(json.data);
var idx = charObjects.length - 1; // get last element index
charObjects[idx].idx = idx; // add new field with index
if (json.data.fileType !== 'charinfo' && json.data.fileType !== 'charsave') {
return throwError("Unsupported file type"); // charitem
}
}
} else if (xhr.readyState === XMLHttpRequest.DONE && xhr.status !== 200) {
// Error. Inform the user
console.log("error");
}
})

formData.append('file', file);

xhr.send(formData)
xhr.onload = function() {
// See response incase it failed...
console.log(xhr)
}
}

我想明白了。

来自npm的FormData((不能以与浏览器相同的容量工作。

我发现request,它的request.form((工作得很好!

var req = request.post({url, form}, function (err, resp, body) {
// console.log(resp)
console.log(form)
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
var form = req.form();
form.append('file', fs.createReadStream('asdgasdgasdg.d2s'));

最新更新