Javascript 如何使用jquery发布文件提交?
我有一个非常简单的网页,允许用户从操作系统中选择一个文件并“提交”到运行node.js的服务器 我现在正在更新前端以使用jQuery,这样我就可以让用户保持在同一个页面上,然后对服务器的响应做一些有用的事情 我添加了jQuery代码,但这样做改变了服务器实际查找(和使用)传递的文件的能力 在发布文件时,我是否需要添加一些特定的内容 相关HTML:Javascript 如何使用jquery发布文件提交?,javascript,jquery,node.js,express,Javascript,Jquery,Node.js,Express,我有一个非常简单的网页,允许用户从操作系统中选择一个文件并“提交”到运行node.js的服务器 我现在正在更新前端以使用jQuery,这样我就可以让用户保持在同一个页面上,然后对服务器的响应做一些有用的事情 我添加了jQuery代码,但这样做改变了服务器实际查找(和使用)传递的文件的能力 在发布文件时,我是否需要添加一些特定的内容 相关HTML: <form id="upload" enctype="multipart/form-data" action="http://localh
<form id="upload" enctype="multipart/form-data"
action="http://localhost:3000/file_upload" method ="post">
<div>
<label for="pickedFile">Upload CSV: </label><input type="file" name="pickedfile" id = "pickedfile"/>
</div>
<div>
<button>Send the file</button>
</div>
</form>
<script src="js/app.js"></script>
相关服务器代码段如下所示:
// site/js/app.js
var app = app || {};
(function($){
})(jQuery);
$(function(){
$("form").submit(function(){
$.post($(this).attr("action"), $(this).serialize(), function(jsonData){
console.log(jsonData);
}, "json");
return false;
});
});
var app = express();
//need to configure this before setting up the routes
//if you want file passing to work correctly
app.configure(function(){
app.use(express.bodyParser());
app.use(app.router);
});
app.post('/file_upload', function(req, res) {
//file should be in req.files.pickedfile
// get the temporary location of the file
// When using jquery, pickedfile is undefined!
var tmp_path = req.files.pickedfile.path;
});
您的Express部分似乎还不错,但是jQuery代码需要一个类似于 ,它处理多部分表单提交:
$("form").ajaxForm({
data: {
extraParam: "foobar"
},
error: function() {
alert("Uh oh, something went wrong");
},
success: function( response ) {
alert("Upload completed!");
console.log( response );
}
});
我用过,而且很满意。我的用例要求我在选择文件后立即自动发送多部分表单。因此我现在让jQuery.form工作(文件已上载),但不会触发成功或错误回调。我是否必须更改服务器响应的某些内容才能让jQuery确认它?不一定。服务器是否已在上载时返回某些内容?如果Express返回的是
204无内容
,浏览器可能不会对响应执行任何操作,或者如果您将响应设置为JSON但返回的不是有效的JSON,jQuery可能会失败。@gustavohenke服务器应该在我上面概述的函数中向其返回JSON对象(res=jsonResult
),但是网页没有得到它,最终在“没有收到数据”的情况下超时。