标签:utf-8 ida rmi Enctype 必须 存储 dir now() ati
通过表单上传文件
<form class="form-horizontal" role="form"
enctype="multipart/form-data" method="POST"
action="/contest/vacation-photo/{{year}}/{{month}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required
id="fieldEmail" name="email">
</div>
</div>
<div class="form-group">
<label for="fieldPhoto" class="col-sm-2 control-label">Vacation photo
</label>
<div class="col-sm-4">
<input type="file" class="form-control" required accept="image/*"
id="fieldPhoto" name="photo">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
必须指定:enctype="multipart/form-data" 来告诉浏览器要上传文件
? 如何上传图片
<input type="file" required accept="image/*" name="photo">
后台通过formidable处理上传文件
var formidable = require(‘formidable‘)
...
// year和month是怎么渲染的
app.post(‘/contest/vacation-photo/:year/:month‘, (req, res) => {
var now = Date.now()
var form = new formidable.IncomingForm({
multiples: true,
// 3.设置上传文件的存储目录
// uploadDir: __dirname + ‘/public/imgs‘
})
// 2.设置编码:如果有普通键值对数据就最好设置
// form.encoding = ‘utf-8‘
// 3.设置上传文件的存储目录 -- 之前把路径写成 __dirname + ‘public/imgs‘ 老报错Emmit
form.uploadDir = __dirname + ‘/public/imgs‘
// 4.设置是否保留文件的扩展名 --若不保留文件的额扩展名,在服务端保存的就是只有文件名没有扩展名的未知文件,
// 如图片:upload_5bb718ac0c1ec3bb318742bcd102a151
form.keepExtensions = true
form.parse(req, function(err, fields, files){
if(err) return res.redirect(303, ‘/html/error.html‘);
console.log(‘received fields:‘);
console.log(fields); // { name: ‘张三丰‘, email: ‘dianziyouxiang@163.com‘ }
console.log(‘received files:‘);
console.log(files); // 上传的图片对象
res.json({ fields, files })
// res.redirect(303, ‘/html/thank-you.html‘);
})
})
标签:utf-8 ida rmi Enctype 必须 存储 dir now() ati
原文地址:https://www.cnblogs.com/tina-12138/p/13291463.html