node进阶| 解决表单enctype=multipart/form-data 时获取不到Input值的问题
生活随笔
收集整理的這篇文章主要介紹了
node进阶| 解决表单enctype=multipart/form-data 时获取不到Input值的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天在學習node踩到一個坑:form設置enctype="multipart/form-data"上傳文件時,無法獲取到表單其他input的值。
因為之前上傳文件用的是?formidable?
方法1:formidable?(無法獲取其他input的值)
引包 app.js
var app = express(); var express = require("express");var router = require("./controller"); //前端MVC的C 一個頂層變量
?
controller/package.json
{"main" :"router.js" }POST請求 app.js:
app.post("/file_upload",router.uploadfile);controller/router:
exports.uploadfile=function(req,res){// console.log(req.route);var form = new formidable.IncomingForm();form.encoding = 'utf-8'; form.uploadDir = "./uploads"; //上傳路徑form.parse(req, function(err, fields, files) { // 表單上傳到東西在fields 文件在files里面//更改文件名var timeStr = (Math.floor(Math.random()*9000+1000)).toString();var d = sd.format(new Date(),'YYYYMMDDHHmmss'+timeStr);var folder = fields.folder;var extname = path.extname(files.file.name); //文件類型var oldName = files.file.path;var newName = "./public/image/"+folder+"/"+d + extname;console.log(newName);console.log(folder);fs.rename(oldName,newName);//成功頁res.send("<a href = '/'>返回</a>");});}views/up.ejs
<form style="width:40%;" method="post" action="/file_upload" enctype="multipart/form-data"><input type="file" id="exampleInputFile" name="file"><input type="submit" class="btn btn-default">上傳</input> </form>但是這種方法無法獲取到form表單其他input的值
方法2:multer(可以獲取)
引包 app.js
var express = require('express'); var path = require('path'); var index = require('./routes/index'); var fs = require('fs'); var multer = require('multer');app.js
app.use('/', index); var storage = multer.diskStorage({destination: function (req, file, cb) {cb(null, './uploads') //設定文件上傳路徑}, //給上傳文件重命名,獲取添加后綴名filename: function (req, file, cb) {console.log(file.originalname) //上傳文件的名字console.log(file.mimetype) //上傳文件的類型console.log(file.fieldname) // 上傳文件的Input的name名console.log(file.encoding) // 編碼方式var fileFormat = (file.originalname).split("."); //采用分割字符串,來獲取文件類型console.log(fileFormat)var extname = path.extname(file.originalname); //path下自帶方法去獲取文件類型console.log(extname);// cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]); //更改名字cb(null, file.fieldname + '-' + Date.now() + extname); //更改名字}}); var upload = multer ({storage:storage}) //定制化上傳參數 app.post('/upload', upload.array('logo',2), function(req, res, next){console.log(req.body.txt)res.send({ret_code: '0'}); });views/index.ejs
<form action="/upload" method="post" enctype="multipart/form-data"><h2>單圖上傳</h2><input type="file" name="logo"><input type="file" name="logo"><input type="text" name="txt"><input type="submit" value="提交"></form>?
multer包成功解決了無法獲取到表單其他input的值的問題。
?
轉載于:https://www.cnblogs.com/dirkhe/p/7354886.html
總結
以上是生活随笔為你收集整理的node进阶| 解决表单enctype=multipart/form-data 时获取不到Input值的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring MVC-视图解析器(Vie
- 下一篇: NS方程求解-PointNet和升维思想