node + react实现文件上传
node + react实现文件上传1. node搭建文件上传的服务器2. 表单上传1. node搭建文件上传的服务器用到的命令npm init -y//初始化npm i express -S//下载包npm i multer _Snode server.js// 开启node服务//server.js文件const expre...
·
node + react实现文件上传
1. node搭建文件上传的服务器
用到的命令
npm init -y //初始化
npm i express -S //下载包
npm i multer _S
node server.js // 开启node 服务
//server.js 文件
const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');
const upload = multer({ dest: 'uploads/' })
const app = express();
// 设置跨域
app.use((req,res,next)=>{
res.set('Access-Control-Allow-Origin','*');
next();
});
// 设置静态资源文件夹为uploads文件夹
app.use(express.static('uploads'));
app.get('/',(req,res)=>{
res.send('Hello world!');
});
app.post('/upload', upload.single('pic'), function (req, res, next) {
// 设置保存的文件和上传的文件名一样
fs.renameSync(req.file.path, path.join('uploads', req.file.originalname));
res.send(req.file.originalname);
});
app.listen(3000,()=>{
console.log('server start at port 3000!');
});
2. 表单上传
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!-- 要上传文件必须先node server.js
上传好的文件会存在upload目录里面
method="post" //form 上传文件默认是get方法 , 要指定
enctype=""
name="pic" // name的属性值根据接口文档确定
-->
<form action="http://localhost:3000/upload" method="post" enctype="multipart/form-data">
<input type="file" name="pic">
<button type="submit">上传</button>
</form>
</body>
</html>
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)