如何使用FormData将文件发送到Nodejs并让Node发回确认消息?

时间:2015-12-22 03:06:30

标签: javascript jquery ajax node.js

您好我正在尝试使用FormData向我的Nodejs服务器发送文件这个简单的表单,但由于某种原因,Node从未接收过它。另外,如何让节点在页面上发回确认消息,说明已收到文件。我做错了什么或者错过了什么?请帮忙。先感谢您。这是我的代码。

HTML

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
 var fd = new FormData();   
 fd.append( 'file', input.files[0] );

$.ajax({
  url: '/uploadfile',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
  alert(data);
  }
});
</script>
</head>
<body>

 <form enctype='multipart/form-data'>
   <input type= "text" name = "theName"/>
   <input type="file" id="file" name="file">
   <input type="submit">
</form>

</body>
</html>

服务器(Nodejs)

 var express = require('express');
 var router = express.Router();

 /* GET users listing. */

 router.get('/', function(req, res){
 res.sendfile('./public/html/form-file.html');
 });

 /* POST file */
 router.post('/', function(req , res){

 console.log('Request received: ');
 console.log(req.body) // this line helps inspect the request so you can see    whether the data is in the url (GET) or the req body (POST)
 console.log('\nRequest recieved: \nmethod: ' + req.method + '\nurl: ' +  req.url) // this line logs just the method and url

 res.end('callback(\'{\"msg\": \"OK\"}\')');

 });

 module.exports = router;

3 个答案:

答案 0 :(得分:4)

这是这个问题的最佳解决方案 - &gt;信用证转到:https://codeforgeek.com/2014/11/ajax-file-upload-node-js/

<强> 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>
$(document).ready(function() {

 $('#uploadForm').submit(function() {
     $("#status").empty().text("File is uploading...");

    $(this).ajaxSubmit({

        error: function(xhr) {
                status('Error: ' + xhr.status);
        },

        success: function(response) {
                console.log(response)
                $("#status").empty().text(response);
        }
   });

  return false;
  });    
});
</script>
</html>

服务器

var express         =       require("express");
var multer          =       require('multer');
var app             =       express();
var upload          =       multer({ dest: './uploads/'});

app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename) {
    return filename+Date.now();
},
onFileUploadStart: function (file) {
    console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
    console.log(file.fieldname + ' uploaded to  ' + file.path)
 }
}));

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");
});

答案 1 :(得分:0)

您的帖子最初没有在您的示例中发送回复

var express = require('express');
var router = express.Router();

/* GET users listing. */

router.get('/', function(req, res){
  res.sendfile('./public/html/form-file.html');
});

/* POST file */
router.post('/', function(req , res){

    console.log('Request received: ');
    console.log(req.body);
    res.json({message: 'file was received'});

 });

 module.exports = router;

然后在你的成功回调中

...
success: function(response) {
    alert(response.message);
}
...

答案 2 :(得分:0)

如何使用强力表,

var formidable = require("formidable");

function imageUpload(req,res){

 var form = new formidable.IncomingForm();

 form.parse(req, function (err, fields, files) {


 console.log("imagePath:"+files.filepath.path);
 //assume <input type = "file" name="filepath">
 res.send("file uploaded");
  });

}