【发布时间】: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;
【问题讨论】:
-
这不是一个重复的问题,因为我使用 Ajax 和 Jquery 进行后端验证。
标签: javascript jquery ajax node.js