Node使用 Express框架,实现文件上传
一 安装依赖包
npm install multer --save
二 客户端上传文件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="http://localhost:3000/test/upload" method="post" enctype="multipart/form-data"> <div> <input name="mobile" placeholder="请输入电话号码"/> </div> <div> <input type="file" name="photo" /> </div> <div> <button type="submit">提交</button> </div> </form> </body> </html>
三 服务器接受文件
const express = require('express'); const router = express.Router(); const mysql = require('mysql'); var multer = require('multer'); var upload = multer({ storage : multer.diskStorage({ // 只能从dest、storage中二选一 destination : (req,file,cb)=>{ cb(null,process.cwd()+'/uploads'); }, filename : (req,file,cb)=>{ // 将上传的文件重新命名 cb(null,file.fieldname+new Date().getTime()+file.originalname.substring(file.originalname.lastIndexOf('.'))); } }) }); let conn = mysql.createConnection({ host : 'localhost', user : 'root', password : '123456', database : 'ionic' }); conn.connect(); /* * 接收图片 */ router.post('/upload',upload.single('photo'),(req,res,next)=>{ res.setHeader('Access-Control-Allow-Origin','*'); // 跨域 let sql = 'update user set photo=? where mobile=?'; let params = [req.file.filename,req.body.mobile]; conn.query(sql,params,(err,result)=>{ // 写入数据库 if(err){ res.json({ code : 0, msg : '[INSERT ERROR] - '+err.message }); }else{ res.json({ code : 1, msg : '上传成功', data : { filename : req.file.filename } }); } }); }); module.exports = router;