Javascript 如何使用nodejs上传文件
我想上传一个带有nodejs的图像 我将文件发送到node,但下面的问题是我不知道如何处理“req” 客户端Javascript 如何使用nodejs上传文件,javascript,html,ajax,node.js,Javascript,Html,Ajax,Node.js,我想上传一个带有nodejs的图像 我将文件发送到node,但下面的问题是我不知道如何处理“req” 客户端 <html> <body> <input id="uploadInput" type="file"/> <div id="uploadShow"></div> <script type="text/javascript"> upload
<html>
<body>
<input id="uploadInput" type="file"/>
<div id="uploadShow"></div>
<script type="text/javascript">
uploadInput = document.getElementById("uploadInput");
uploadInput.onchange = function() { //when file ready to upload
if(uploadInput.files && uploadInput.files[0]) {
var file = uploadInput.files[0]; //I want to send the file
var xhr = new XMLHttpRequest();
if (xhr.readyState == 4 && xhr.status == 200) {
var uploadShow = document.getElementById("uploadInput");
uploadShow.innerHTML = xhr.responseText; //show file
}
xhr.open('POST', "/upload", false);
xhr.send(file); //send file...
}
};
</script>
</body>
</html>
如何上传图像并显示?我不认为文件上传会以这种方式工作。如果您可以使用express,我建议您使用强大的支持ajax的文件上传
请在此处查看:
文件[0]
可能不会真正提供文件,更像是一个具有高度、宽度和url的对象'fakepath/image.png'
或其他内容,而这只是一个字符串。图像将位于formData对象中。
var http = require('http'),url = require("url"),
path = require('path'),fs = require('fs');
http.createServer(function(req, res) {
var filename = "/index.html";
if (req.url !== "/") {
filename = url.parse(req.url, true).pathname;
filename = filename.split("?")[0];
}
if (filename === "/upload" && req.method.toLowerCase() == 'post') {
//deal the request of ajax
**upload_file**(req, res); //can you help me to write this function
return;
}
//the following fs.readFile index.html
}).listen("192.168.39.9", 8888);