我在客户端使用http请求将图片存储到mongodb服务器时遇到了麻烦。非常感激您的帮助,我需要一个简单的示例,说明如何将图像文件作为数据添加到http post请求中,例如XMLhttprequest。假设我知道服务器方法的URL,图像的来源在__内定义。
imgsrc
一个文件的名称被存储在中。name
我有这个自动取款机:
var http = new XMLHttpRequest();
httpPost.onreadystatechange = function(err) {
if (httpPost.readyState == 4 && httpPost.status == 200){
console.log(httpPost.responseText);
} else {
console.log(err);
}
}
var path = "http://127.0.0.1:8000/uploadImage/"+name;
httpPost.open("POST", path, true);
// I guess I have to add the imagedata into the httpPost here, but i dont know how
httpPost.send(null);
然后在服务器端的路径上,将调用以下方法,并且我希望将base64编码图像的URL存储在mongodb中。我该如何从httpPost访问该图像?
function postNewImageType(req, res, next){
var newImageTypeData = {
name: req.params.name,
image: "placeholder.png"
}
var data = // how to access the image?
var imageBuffer = decodeBase64Image(data);
fs.writeFile(cfg.imageFolger+newImageTypeData._id+'.jpeg', imageBuffer.data, function(err){
if (err) return new Error(err);
newImageTypeData.set({image:newImageTypeData._id+'.jpeg'});
var image = new ImageType(newImageData);
});
imagetype.save(function (err) {
if (error) {return next(new restify.InvalidArgumentError(JSON.stringify(error.errors)));}
else { res.send(201, imagetype);}
});
}