欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

Nodejs 文件上传

发布时间:2023/12/9 42 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Nodejs 文件上传 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

node js 接收表单数据原理

/*** node js 接收表单数据*/ const http = require("http"); const qs = require("querystring");http.createServer((request, response) => {// 表单提交的原理if (request.url === "/post" && request.method.toLowerCase() === "post") {// 1. 设置接收的变量let formData = "";// 2. 接收小段数据request.on("data", buf => {formData += buf;});// 3. 监听所有数据传递完毕事件request.once("end", () => {formData = qs.parse(formData);console.log(formData); // objectconsole.log("数据接收完成");});} }).listen(3000);

使用 formidable 上传文件

/*** 使用formidable上传图片*/ const http = require("http"); const fs = require("fs"); const formidable = require("formidable"); const uuidv1 = require("uuid/v1"); const path = require("path");http.createServer((request, response) => {if (request.url == "/") {fs.readFile(__dirname+"/index.html", (err, data)=>{if (err) {throw err;}response.setHeader("content-type", "text/html;charset=utf8;");response.end(data.toString());});}if (request.url === "/post" && request.method.toLowerCase() === "post") {// 1.实例化对象const form = new formidable();// 2.设置文件上传的路径, 默认就会自动上传到这个目录中,这个目录必须要存在,否则报错, 不建议使用相对路径form.uploadDir = __dirname + '/uploads';// 3.获取表单内容form.parse(request, (err, fields, files)=> {/****************** 利用formidable的文件名// 3.1 获取原文件名let ext = path.extname(files.file.name);// 3.2 获取上传文件的路径let oldPath = files.file.path;// 3.3 拼接新路径let newPath = oldPath + ext;console.log(newPath);// 3.4 修改文件名或者使用 uuid 这个包, 二选一************************************/// 3.1 获取独一无二的一个字符串 uuid let uuid = uuidv1();// 3.2 获取上传文件的后缀let ext = path.extname(files.file.name);// 3.3 获取路径let oldPath = files.file.path;let newPath = __dirname + "/uploads/" + uuid + ext;// 3.4 修改文件名fs.rename(oldPath, newPath, err=>{if (err) throw err;response.end("文件上传成功");});response.end("images");});}// response.end("404"); }).listen(3000);

转载于:https://www.cnblogs.com/liaohui5/p/10581624.html

总结

以上是生活随笔为你收集整理的Nodejs 文件上传的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。