【发布时间】:2016-11-15 13:10:15
【问题描述】:
我正在尝试上传我的图像并将其自动保存到我的数据库 (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?谢谢。
【问题讨论】:
-
错误很明显,在浏览器中你没有定义
status()函数,但是你试图在你的error处理程序中使用它。 -
另外,如果你想将文件直接流式传输到 mongodb,你需要下拉到像
busboy这样的模块,它可以让你访问文件流。