Node.js,Express:如何使用客户端处理res.send 值
Node.js, Express: How can I handle res.send values with the client
我是node.js的新手,我也在使用express。
我构建了一个简单的 Web 应用程序来将文件上传到服务器,并在它们没问题时保存它们。这工作正常,但现在我想通知客户端当前状态(它是上传还是不起作用,因为文件很大)。
我知道我应该使用 res.send()
,但我想在客户端上传文件的同一页面上显示它(所有元素都在"upload.html"上)。我想,我必须使用客户端 javascript 来处理发送的信息,但是我如何与服务器端 javascript 和客户端 javascript 通信?还是我不需要使用客户端JavaScript?
(我想稍后将其与HTML结合使用,以便我可以使用CSS从服务器设计答案。
服务器.js:
var express = require('express'),
fileUpload = require('express-fileupload'),
fs = require('fs'),
obSizeOf = require('object-sizeof'),
app = express();
app.use(express.static("public"));
app.use(fileUpload());
app.get("/upload.html", function(req, res){
res.sendfile(__dirname + "/" +"upload.html");
})
app.post('/upload.html', function(req, res) {
if(obSizeOf(req.files.sampleFile) > 10000000)
{
res.send("The size of the not-uploaded file is to large! Please use a file with a maximal size of 10MB");
return;
}
else
{
var sampleFile;
if (req.files.sampleFile.name == "") {
res.send('No files were uploaded.');
return;
}
else
{
sampleFile = req.files.sampleFile;
var typ = sampleFile.mimetype.split("/");
console.log(typ[0]);
if(fs.existsSync("public/upload/image/"+typ[0]+"/"+sampleFile.name))
{
res.send("A File with the same name already exists! Please rename it!");
return;
}
else
{
sampleFile.mv('public/upload/'+typ[0]+'/'+sampleFile.name , function(err) {
if (err){
res.send('File NOT UPLOADED!');
}
else { console.log("Mieeep!"); res.send(typ[0].charAt(0).toUpperCase()+typ[0].slice(1) +' data uploaded!');
}
});
}
}
}
});
app.listen("8000");
/上传.html:
<html>
<body>
<form ref='uploadForm'
id='uploadForm'
action='/upload.html'
method='post'
encType="multipart/form-data">
Upload File
</br>
<input type="file" name="sampleFile" />
</br>
<input type='submit' value='Upload!' />
</br>
<p id="serverInformation"></p> <!--Placeholder for information from the server-->
Only images
</form>
</body>
</html>
你真正需要的是套接字编程。使用节点js,您可以轻松做到这一点。
只需查看此链接即可了解有关套接字和节点JS的更多信息。
您可以使用 AJAX 并检查错误状态。
...<script>
$(document).ready(function() {
$("#uploadForm").submit(function() {
$.ajax({
type: "POST",
url: "/upload.html",
data: $(this).serialize(),
complete: function(xhr, statusText){
alert(xhr.status+" : "+ statusText);
}
})
})
})
</script>
相关文章:
- Nodejs和express路由,如何处理客户端的承诺
- 实现客户端WebHook处理程序
- 无需刷新即可进行简单的客户端文件处理
- 如何在不使用处理程序的情况下使用ajax将文件从客户端发送到服务器端
- 在客户端的 IFRAME 中对内容进行沙盒处理
- 在服务器端禁用 aspxgridviews,如何在客户端处理
- 在客户端断开连接时释放事件处理程序 Socket.IO
- 简单客户端应用程序中的文件处理
- 如何处理客户端 剑道网格中的错误处理
- 没有客户端 URL 处理的动态网站
- 如何处理客户端节点上的异步请求
- 如何处理客户端运行的 JavaScript 中的意外值
- 正在处理客户端的会话超时
- SignalR处理客户端超时事件
- 目前接受的在浏览器窗口中处理客户端会话信息的无cookie方法
- 使用vb.net处理客户端和服务器端
- 通过排队机制处理客户端脱机http请求
- 如何处理客户端关闭Javascript
- 预处理客户端'使用Java和GWT将本地csv文件数据转换为数组
- 代码处理(客户端而不是在服务器上)