文件上传至服务器的方式有多种,下面要介绍的 formidable 是其中之一
Web side
- The method of submitting a file upload request on the front-end Web side can be implemented in the form of a form
- Upload file to server form must bring
enctype
attributes " - Upload method
POST
<h5>formidable 文件上传 /reg</h5>
<form action="/reg" method="POST" enctype="multipart/form-data">
<input type="file" name="pho"><br>
<input type="submit" value="文件上传">
</form>
Node server
- $ npm install formidable npm install the formidable module (the installed files are in the node_modules folder)
- require (“formidable”) import module
- Use express to build the server (express can't be used basically, you can come to express express quickly )
const formidable = require("formidable");
const fs = require("fs");
const path = require("path")
const express = require("express");
const app = express();
app.use("/", express.static("./directorys"));
app.post("/reg", (req, res) => {
let form = new formidable.IncomingForm();
form.uploadDir = "./directorys/pho";
// 执行回调函数,请求则全部就收完毕
form.parse(req, (err, fields, files) => {
// console.log(fields); // 所有的文本域、单选框都在 fields 对象中
console.log(files); // 所有的文件域都在 files 中
let time = new Date().getTime();
let numRan = parseInt(Math.random() * 89999 + 10000);
let extname = path.extname(files.pho.name);
// 原始文件名
let oldName = __dirname + "/" + files.pho.path;
// 新文件名
let newName = __dirname + "/directorys/pho/" + time + numRan + extname;
console.log(oldName,newName);
// 改名(剪切)
fs.rename(oldName,newName,err => res.end("改名完成!"));
});
});
app.listen(3000);
Initial folder
Terminal folder
after upload