[英]How to post a image information from front end to back end via ajax
Front end js: 前端js:
var newUser = {
'username': $('#addUser fieldset input#inputUserName').val(),
'email': $('#addUser fieldset input#inputUserEmail').val(),
'fullname': $('#addUser fieldset input#inputUserFullname').val(),
'age': $('#addUser fieldset input#inputUserAge').val(),
'sex': $('input:radio[name="sex"]:checked').val(),
'profileimage':$('input[name="profileimage"]').val()
}
console.log($('input[name="sex"]').val());
// use AJAX to post object to adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON'
}).done(function (response) {...
Back End js(use express.js and multer) 后端js(使用express.js和multer)
router.post('/adduser', upload.single('profileimage'), function (req, res) {
var db = req.db;
var collection = db.get('userlist');
var username = req.body.username;
var email = req.body.email;
var age = req.body.age;
var sex = req.body.sex;
var fullname = req.body.fullname;
if (req.file) {
var profileimage = req.file.filename;
} else {
var profileimage = 'noimage.jpg';
}
collection.insert({
"username": username,
"email": email,
"age": age,
"sex": sex,
"fullname": fullname,
"profileimage": profileimage
}, function (err, result)...
The code above is not work. 上面的代码不起作用。 And what should I do insert the image information to my mongoDB database, and could display it as well. 而且我应该怎么做将图像信息插入到我的mongoDB数据库中,并可以显示它。
I believe you're looking for the File Reader in Javascript. 我相信您正在寻找Javascript中的File Reader 。 Here is some excellent documentation on how to use the readAsDataURL which will allow you to interact with a byte array of the file and submit it into a database as a blob or byte array. 这是一些有关如何使用readAsDataURL的出色文档,该文档使您可以与文件的字节数组进行交互,并将其作为Blob或字节数组提交到数据库中。
Formdata could help to do this, problem solved. 问题解决了,Formdata可以帮助实现这一点。
var newUser = new FormData();
newUser.append('username', $('#addUser fieldset input#inputUserName').val());
newUser.append('email', $('#addUser fieldset input#inputUserEmail').val());
newUser.append('fullname', $('#addUser fieldset input#inputUserFullname').val());
newUser.append('age', $('#addUser fieldset input#inputUserAge').val());
newUser.append('sex', $('input:radio[name="sex"]:checked').val());
newUser.append('profileimage', $('#uploadImage')[0].files[0]);
console.log($('input:radio[name="sex"]:checked').val());
//console.log(newUser);
// use AJAX to post object to adduser service
$.ajax({
type: 'POST',
data: newUser,
url: '/users/adduser',
dataType: 'JSON',
contentType: false,
processData: false
}).done(function (response) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.