[英]Upload an image from client to the NodeJS server and save it internaly on the server?
How I am able to upload an image from the client part, and send it by making an HTTP request(POST) to the sever(NodeJS) and save it internally on the server. 我如何从客户端上传图像,并通过发出HTTP请求(POST)将其发送到服务器(NodeJS)并将其内部保存在服务器上。
Be it Jquery use or XMLHttpRequest use or even form use, I stumble on the same problem, can't get the image on the sever side thus can't store it internally. 无论是Jquery使用还是XMLHttpRequest使用,甚至是表单使用,我都在同一问题上绊倒,无法在服务器端获取图像,因此无法在内部存储它。
Code I've tried for the client side: 我为客户端尝试过的代码:
let img = document.createElement("img");
img.src = "./public/assets/img.png";
img.addEventListener("load", (e) => {
addParkingSource(img);
});
function addParkingSource(image) {
let blobFile = image;
let formData = new FormData();
formData.append("fileToUpload", blobFile);
$.ajax({
url: "http://localhost:8000/post-image",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response) {},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
}
The sever side, I can't read it, whenever I try to read the data property of req(request) it gives empty object, but the Content-Length points to a number > 0, which means the image was sent successfully. 服务器端,我无法读取它,每当我尝试读取req(request)的data属性时,它都会提供一个空对象,但是Content-Length指向一个大于0的数字,这意味着图像已成功发送。
app.post("/post-image", function(req, res) {
console.log(req.body);
});
Note: I have no issue with cors right now. 注意:我现在对cors没问题。
What I am doing wrong and how can I correctly do implement it? 我在做什么错,如何正确实施呢?
I would suggest you to use multer
npm
package
for file uploaded tasks. 我建议您使用
multer
npm
package
执行文件上传任务。
https://github.com/expressjs/multer https://github.com/expressjs/multer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.