【问题标题】:How to send a file to Nodejs using FormData and have Node send back a confirmation message?如何使用 FormData 将文件发送到 Nodejs 并让 Node 发回确认消息?
【发布时间】:2016-03-28 05:54:44
【问题描述】:

您好,我正在处理这个简单的表单,尝试使用FormData 将文件发送到我的 Nodejs 服务器,但由于某种原因,Node 从未收到它。另外,如何让 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;

【问题讨论】:

标签: javascript jquery ajax node.js


【解决方案1】:

这是这个问题的最佳解决方案 -> 致谢: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");
});

【讨论】:

    【解决方案2】:

    如何使用强大的,

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

    【讨论】:

      【解决方案3】:

      您的帖子最初没有在您的示例中发送响应

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

      【讨论】:

      • 你知道 JSON 不能有一个保存文件值的属性吗?
      • html 文件是什么样子的?
      猜你喜欢
      • 1970-01-01
      • 2021-02-17
      • 2016-04-19
      • 2021-09-26
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-29
      相关资源
      最近更新 更多