本文介绍了如何使用FormData将文件发送到Nodejs并让Node发回确认消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi I'm working on this simple form trying to send a file to my Nodejs server using FormData, but for some reason Node never receives it. Also How can I have Node send back a confirmation message on the page saying that file was received. What is it that I'm doing wrong or missing?. Please help. Thank you in advance. Here's my code.

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;


推荐答案

这是这个问题的最佳解决方案 - >积分:

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

这篇关于如何使用FormData将文件发送到Nodejs并让Node发回确认消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 08:40