0
保存上傳到node.js文件的最佳方式是什麼?Node.js:如何從瀏覽器窗體保存上傳的文件?
保存上傳到node.js文件的最佳方式是什麼?Node.js:如何從瀏覽器窗體保存上傳的文件?
Express是圍繞由nodejs核心模塊提供的原始Http模塊構建的。看看該文檔約http.createServer
因爲每個req
和res
在requestListener是一個流,你其實可以與fs
核心模塊做到這一點很容易。
var http = require('http');
var fs = require('fs');
var server = http.createServer(function requestListener (req, res) {
req.once('end', function onEnd() {
res.statusCode = 200;
res.end('Uploaded File\n');
});
req.pipe(fs.createWriteStream('./uploadedFile.txt'));
});
server.listen(8080);
嘗試上傳文件:
# file contains "hello world!"
curl -v -d @test.txt localhost:8080
* Rebuilt URL to: localhost:8080/
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> POST/HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
> Content-Length: 12
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 12 out of 12 bytes
< HTTP/1.1 200 OK
< Date: Fri, 21 Apr 2017 01:34:21 GMT
< Connection: keep-alive
< Content-Length: 14
<
Uploaded File
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
,並檢查了文件
cat uploadedFile.txt
hello world!
希望這有助於!