首页 > 解决方案 > 将图像上传到 Node.JS 服务器而不使用

问题描述

我有一个 node.js 服务器,它使用 express-fileupload 来接受图像。现在我正在研究上传图片的功能。但是我不想使用<form>,因为我更喜欢xhtml请求,原因有很多,但主要是因为我不想在用户上传图片后重定向用户。

我尝试将图片作为 dataURI 读取,将其发送到服务器,对其进行解码并将其写入文件,但这不起作用并且似乎资源密集且费力。

//I used the dataString from the callback method and wrote it to a file using fs.writeFile
function dataURItoimage(dataString, callback){
   const atob = require("atob");

   dataString.replace("data:image/jpeg;base64,", "");
   dataString.replace("data:image/png;base64,", "");

   atob(dataString);
   callback(null, dataString);
}
//User side code
avatarInput.addEventListener("change", (e) => {
    const reader = new FileReader();
    reader.readAsDataURL(avatarInput.files[0]);
    reader.onload = () => {
        avatar = reader.result;
        tosend.avatar = reader.result;
    }
}, false);

uploadButton.onclick = () => {
    var request = new XMLHttpRequest();
    request.open("POST", "/avatarUpload");
    request.setRequestHeader("Content-Type", "application/json");

    var tosend = {avatar: ""};
    tosend.avatar = avatar;

    request.send(JSON.stringify(tosend));
}

有没有更好的方法将用户可以选择的图像上传到 node.js 服务器?

标签: javascriptnode.jsimage-uploading

解决方案


所以我这样做了:

    var request = new XMLHttpRequest();
    request.open("POST", "/test");

    var fd = new FormData();
    fd.append("file", avatarInput.files[0]);
    request.send(fd);

我创建了一个 FormData 对象,附加了用户在名为“avatarInput”的输入中选择的图像,并将该对象发送到服务器。在服务器端,我使用 express-fileupload 来访问文件:

app.post("/test", (req, res) => {
    if(req.files){
        //With the follwing command you can save the recieved image
        req.files.file.mv("./file.png",  (err) => {if(err)throw err});
    }
    res.end();
});

推荐阅读