[Express] Upload Files with Express
2024-08-31 20:41:43
In this lesson we create a new Express web server app for handling file uploads and persisting them to the filesystem. We will walk through using the express-fileupload middleware module from npm to process file uploads, and then use the Express static middleware to serve the uploaded file as a static asset.
const path = require('path');
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express(); app.use(fileUpload());
app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); app.get('/', (req, res) => {
res.send(`
<form action="/upload" enctype="multipart/form-data" method="post">
<input type="file" name="foo" /><br /><br />
<input type="submit" value="Upload" />
</form>
`);
}); app.post('/upload', (req, res) => {
if (!req.files) return res.status(400).send('No files were uploaded!'); const { foo } = req.files;
const uploadTo = `uploads/${foo.name}`; foo.mv(uploadTo, (err) => {
if (err) return res.status(500).send(err); res.send(`File uploaded to <a href="${uploadTo}">${uploadTo}</a>`);
});
}); app.listen(8080, () => {
console.log('Server listening on port 8080!');
});
最新文章
- Gulp: Getting Started
- 在C#后端处理一些结果然传给前端Javascript或是jQuery
- 树莓派学Python博客收集
- 【转】15 个用于 GitHub 的 Chrome 插件
- SQLserver利用系统时间生成“2015-11-30 00:00:00.000”类型的时间
- 信号量和PV操作写出Bakery算法的同步程序
- range([start], stop[, step]):产生一个序列,默认从0开始
- 使用APMServ本地搭建多个网站
- 使用Emacs:生存篇
- jq实战-表单验证
- salesforce lightning零基础学习(十三) 自定义Lookup组件(Single &; Multiple)
- たくさんの数式 / Many Formulas AtCoder - 2067 (枚举二进制)
- MyBatis笔记----MyBatis数据库表格数据修改更新的两种方法:XML与注解
- python 逻辑判断 循环练习题
- [leetcode]Unique Paths @ Python
- redis内部数据结构深入浅出
- 开源作业调度框架 - Quartz.NET - Cron表达式测试
- (匹配 匈牙利)棋盘游戏 -- Hdu --1281
- 一款jquery实现的整屏切换特效
- URL Scheme