2016-11-15 57 views
-1

我在上传图片并将其自动保存到我的数据库(mongodb)。但我坚持上传图片。这里是我的server.js:将图片上载到html

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

错误很明显,在浏览器中你没有定义'status()'函数,但是你正在试图在你的'error'处理程序中使用它。 – mscdex

+0

另外,如果你想直接将文件流式传输到mongodb,你需要下载一个像'busboy'这样的模块,它可以为你提供对文件流的访问。 – mscdex

回答

0

你上线28得到一个错误:

  status('Error: ' + xhr.status); 

你可能想改变这一行:

$("#status").empty().text('Error: ' + xhr.status); 

这不会解决你的问题,但它应该显示上传错误,所以你可以采取下一步。祝你好运!

+0

它适用于上传问题,但404错误仍然存​​在 –