1. 程式人生 > >node之上傳檔案(form表單)

node之上傳檔案(form表單)

1.安裝依賴模組

node上傳檔案首先要安裝依賴模組:

npm install fs multer path

這三個模組是上傳檔案所必須的

2.前端

form表單上傳檔案必須要設定引數 enctype=”multipart/form-data”
程式碼如下:

<form action="/file.html" method="post" enctype="multipart/form-data">
<input type="file" name="wenjian">
<input type="submit" value="提交">

3.後臺

在node後臺程式碼中,先引入模組

var express = require('express');
var router = express.Router();
var fs = require('fs')
var multer = require('multer')
var path = require('path');
var bin = multer({dest:'bin'});//用來儲存檔案的資料夾名稱

router.post('/file.html',bin.single('wenjian'),function(req,res,next){
    console
.log(req.body.name); var filename = req.file.originalname; console.log(req.file); fs.renameSync('./bin/'+req.file.filename,'./bin/'+req.body.name+'/'+filename); res.render('file', {}); }); module.exports = router;