繁体   English   中英

在不使用的情况下将图像上传到 Node.JS 服务器<form>

[英]Upload images to a Node.JS server without using <form>

我有一个 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 服务器?

所以我是这样做的:

    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();
});

你可以试试这个例子。 它对我有用。 我希望它能帮助你。

发送 dataURL 抛出 Ajax 请求:

const dataURL = snapshotCanvas.toDataURL('image/png');
$.ajax({
    url: 'http://localhost:3000/upload-image',
    dataType: 'json',
    data: { data: dataURL },
    type: 'POST',
    success: function(data) {}
});

接收请求:

router.post('/', (req, res) => {
    const base64 = req.body.data.replace(/^data:image\/png;base64,/, "");
    fs.writeFileSync(`uploads/images/newImage.jpg`, base64, {encoding: 'base64'});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM