javascript - 将图像上传到 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 服务器?
解决方案
所以我这样做了:
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();
});
推荐阅读
- android - 使用不同货币的计费客户订阅
- html - 在 Fetch 语句中获取 React Js 中的用户输入
- php - Symfony 中序列化服务的问题:不允许序列化“SimpleXMLElement”
- python - 需要帮助使用 Python 检索 Google cloudSQL 元数据和日志
- apostrophe-cms - 将预定义的小部件添加到主页
- kubernetes - 带有后缀的 Kubernetes Ingress 后端路径
- php - 使用 phpmailer 通过电子邮件发送 html 页面
- azure - Azure DevOps 管道卡住
- r - ggplot将y轴数值更改为文本
- javascript - 为什么 iframe 内的 iframe 不能执行 window.top.addEventListener?