无需使用即可将图像上传到Node.JS服务器

问题描述 投票:1回答:2

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

javascript node.js image-uploading
2个回答
1
投票

所以我这样做了:

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

0
投票

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

通过Ajax请求发送数据URL:

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'});
}
© www.soinside.com 2019 - 2024. All rights reserved.