我正在尝试上传我的图片并将其自动保存到我的数据库(mongodb)。但我坚持上传图片。这是我的server.js:
var express = require("express");
var multer = require('multer');
var app = express();
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
var upload = multer({ storage : storage}).single('userPhoto');
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3000,function(){
console.log("Working on port 3000");
});
这是我的index.html:
<!DOCTYPE html>
<html>
<head>
<title>File upload Node.</title>
</head>
<body>
<form id="uploadForm"
enctype="multipart/form-data"
action="/api/photo"
method="post">
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
<span id = "status"></span>
</form>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<script>
$(document).ready(function() {
$('#uploadForm').submit(function() {
$("#status").empty().text("File is uploading...");
$(this).ajaxSubmit({
error: function(xhr) {
status('Error: ' + xhr.status);
},
success: function(response) {
$("#status").empty().text(response);
console.log(response);
}
});
//Very important line, it disable the page refresh.
return false;
});
});
</script>
</html>
我尝试运行时遇到此错误
POST http://localhost:8051/api/photo 404 ()
send @ jquery.min.js:4
ajax @ jquery.min.js:4
o @ jquery.form.min.js:1
e.fn.ajaxSubmit @ jquery.form.min.js:1
(anonymous function) @ (index):25
dispatch @ jquery.min.js:3
i @ jquery.min.js:3
(index):28
Uncaught TypeError: status is not a function(…)
error @ (index):28
t.error @ jquery.form.min.js:1
n @ jquery.min.js:2
fireWith @ jquery.min.js:2
w @ jquery.min.js:4
d @ jquery.min.js:4
我的问题是,如何修复错误以及如何将图像保存到mongodb?三江源。
答案 0 :(得分:0)
你在第28行遇到错误:
status('Error: ' + xhr.status);
您可能希望将该行更改为:
$("#status").empty().text('Error: ' + xhr.status);
这不会解决您的问题,但它应该显示您正在获取的上传错误,以便您可以采取下一步措施。祝你好运!