安装npm install formidable
先把文件上传到临时文件夹,再通过fs重命名移动到指定的目录即可
fs.rename即重命名,但是fs.rename不能夸磁盘移动文件,所以我们需要指定上传的临时目录要和最终目录在同一磁盘下
前段请求
方法1:使用form标签和submit提交
form(action='/uploadImg', method="post", enctype="multipart/form-data" )
input(type="file", id="file1", name="file1")
br
button(type="submit", id="bt1", name="bt1") upload
方法2:ajax,post提交
input(type="file", id="file1", name="file1")
button(id="upload", name="upload") submit
javascript方法
$("#upload").click(function(){
var data = new FormData();
var files = $("#file1")[0].files;
if(files){
data.append("file", files[0]);
}
$.ajax({
type: 'post',
dataType: 'json',
data : data,
contentType: false,
processData: false,
success : function () {}
}
上传实现方法:form解析后的files是个对象,所以可以实现多文件上传
tool.uploadImg =function(req, res){
var fs = require('fs');
var formidable = require("formidable");
var form = new formidable.IncomingForm();
form.uploadDir = "./public/upload/temp/";//改变临时目录
form.parse(req, function(error, fields, files){
for(var key in files){
var file = files[key];
var fName = (new Date()).getTime();
switch (file.type){
case "image/jpeg":
fName = fName + ".jpg";
break;
case "image/png":
fName = fName + ".png";
break;
default :
fName =fName + ".png";
break;
}
console.log(file.size);
var uploadDir = "./public/upload/" + fName;
fs.rename(file.path, uploadDir, function(err) {
if (err) {
res.write(err+"\n");
res.end();
}
res.write("upload image:<br/>");
res.write("<img src='/imgShow?id=" + fName + "' />");
res.end();
});
}
});
};
显示上传后的文件
tool.imgShow = function(req, res){
var fs = require("fs");
var arg = tool.handleGetArg(req, res);
var uploadDir = "./public/upload/" + arg["id"];
fs.readFile(uploadDir, "binary", function(err, file){
if(err){
res.write(err+"\n");
res.end();
}else{
res.write(file, "binary");
res.end();
}
});
};