分享

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

 印度阿三17 2019-06-23

嗨,我正在研究这个简单的表单,尝试使用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;

解决方法:

这是这个问题的最佳解决方案 – >学分归于:https:///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./ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 <script src="http://cdnjs./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");
});
来源:https://www./content-1-261001.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多