[英]How to upload file with nodejs
I want to uplaod an image with nodejs. 我想用nodejs修饰图像。
I send the file to node, but the follow question is that I don't know how to deal the "req". 我将文件发送到节点,但是接下来的问题是我不知道如何处理“请求”。
Client 客户
<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>
Server 服务器
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);
How can I upload a image and show? 如何上传图片并显示?
I don't think file uploads will work that way. 我认为文件上传不会那样工作。 If you're okay using express, I will suggest you use formidable supported ajax file upload; 如果可以使用Express,我建议您使用强大的受支持的Ajax文件上传;
Check it out here: https://stackoverflow.com/a/20372845/1520518 在此处查看: https : //stackoverflow.com/a/20372845/1520518
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.