簡體   English   中英

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從服務器設計答案。)

server.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"); 

/upload.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> 

您真正需要的是套接字編程。 使用node 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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM