【问题标题】:Equivalent of fs.readFile() -> to -> HTML upload in DOM等效于 fs.readFile() -> 到 -> 在 DOM 中上传 HTML
【发布时间】:2026-01-04 07:10:01
【问题描述】:

我正在尝试通过主要改造一些现有的 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)
    }
}

【问题讨论】:

    标签: javascript node.js api xmlhttprequest multipartform-data


    【解决方案1】:

    我想通了。

    来自 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'));

    【讨论】:

      最近更新 更多