当前位置: 首页 > news >正文

node学习系列之简单文件上传

此为看完node入门写的小demo,自己实现了一遍,借助的外部模块只有formidable
Node.js的Formidable模块的使用

index.js

const server = require('./server');
const router = require('./router.js');
const requestHandler = require('./requestHandler.js');

var handle = {};
handle['/'] = requestHandler.start;
handle['/start'] = requestHandler.start;
handle['/upload'] = requestHandler.upload;
handle['/show'] = requestHandler.show;

server.start(router.route, handle);

server.js

const http = require('http');
const url = require('url');

const start = (route, handle) => {
    http.createServer((request, response) => {
        let pathname = url.parse(request.url).pathname;
        let postData = '';
        console.log('request from' + pathname + 'received');

        route(handle, pathname, response, request);

    }).listen(8888);
}

console.log('server has started');

module.exports = {
    start: start
}

router.js

const route = (handle, pathname, response, request) => {
    console.log('about to route a request for' + pathname);
    if(typeof handle[pathname] === 'function') {
        handle[pathname](response, request);
    }else {
        console.log('no request handle found for ' + pathname);
        response.writeHead(404, {'Conten-Type': 'text/plain'});
        response.write('404 not found');
        response.end();
    }
}

module.exports = {
    route: route
}

requestHandler.js

const querystring = require('querystring');
const fs = require('fs');
const formidable = require('formidable');

const start = (response, request) => {
    console.log('request handle "start" was called');
    let body = `<html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>Document</title>
                </head>
                <body>
                    <form action="/upload" method="post" enctype="multipart/form-data">
                        <input type="file" name="upload">
                        <input type="submit" value="submit">
                    </form>
                </body>
                </html>`;
    response.writeHead(200, {'Conten-Type' : 'text/html'});
    response.write(body);
    response.end();
    
}

const upload = (response, request) => {
    console.log('request handle "upload" was called');
    let form = new formidable.IncomingForm();
    form.uploadDir = './upload/tmp';
    form.parse(request, (err, fields, files) => {
        console.log('parse done');
        let body = `<html lang="en">
                    <head>
                        <meta charset="UTF-8">
                        <title>Document</title>
                    </head>
                    <body>
                    <img src="/show" />
                    </body>
                    </html>`;
        fs.renameSync(files.upload.path, '/tmp/test.png')
        response.writeHead(200, {'Content6-Type' : 'text/html'});
        response.write(body);
        response.end();
        
    })
}

const show = (response) => {
    console.log('request handle "show" was called');
    fs.readFile('/tmp/test.png', "binary", (err, file) => {
        if(err) {
            response.writeHead(500, {'Conten-Type' : 'text/plain'});
            response.write(err);
            response.end();
        }else {
            response.writeHead(200, {'Conten-Type' : 'image/png'});
            response.write(file, "binary");
            response.end();
        }
    })
}

module.exports = {
    start: start,
    upload: upload,
    show: show
}

原代码仓库

learn-node/upload

相关文章:

  • 前端 关于汇率的计算
  • mongoDB 文档查询
  • 安装了python报错 或者执行 npm install 时报node-sass的各种相关错误 解决办法
  • 今天打开一个网站 FSO对象实例创建失败
  • 【LeetCode】5. Longest Palindromic Substring 最大回文子串
  • vu2响应式原理 代码分析
  • 希尔排序
  • vu3响应式原理 代码分析
  • Java Tomcat SSL 服务端/客户端双向认证(一)
  • vue3中 setup注意点
  • redis简介
  • 《Spark GraphX in Action》书评及作者访谈
  • vue3的 computed 计算属性 与 watch监听
  • Diomidis Spinellis:有效的调试
  • ListView的简单使用
  • Android 控件背景颜色处理
  • Angular 2 DI - IoC DI - 1
  • Bootstrap JS插件Alert源码分析
  • ECMAScript入门(七)--Module语法
  • ES6简单总结(搭配简单的讲解和小案例)
  • HTML-表单
  • in typeof instanceof ===这些运算符有什么作用
  • Java 23种设计模式 之单例模式 7种实现方式
  • MaxCompute访问TableStore(OTS) 数据
  • Otto开发初探——微服务依赖管理新利器
  • PhantomJS 安装
  • React+TypeScript入门
  • Redis在Web项目中的应用与实践
  • SwizzleMethod 黑魔法
  • 第十八天-企业应用架构模式-基本模式
  • 浮动相关
  • 开放才能进步!Angular和Wijmo一起走过的日子
  • 前端_面试
  • 人脸识别最新开发经验demo
  • 线性表及其算法(java实现)
  • #基础#使用Jupyter进行Notebook的转换 .ipynb文件导出为.md文件
  • (03)光刻——半导体电路的绘制
  • (2)MFC+openGL单文档框架glFrame
  • (2021|NIPS,扩散,无条件分数估计,条件分数估计)无分类器引导扩散
  • (附源码)springboot猪场管理系统 毕业设计 160901
  • (剑指Offer)面试题41:和为s的连续正数序列
  • (十二)python网络爬虫(理论+实战)——实战:使用BeautfulSoup解析baidu热搜新闻数据
  • (十三)Flask之特殊装饰器详解
  • (译)2019年前端性能优化清单 — 下篇
  • (转载)hibernate缓存
  • ***php进行支付宝开发中return_url和notify_url的区别分析
  • ***详解账号泄露:全球约1亿用户已泄露
  • ./indexer: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object fil
  • .NET CLR基本术语
  • .NET CORE 3.1 集成JWT鉴权和授权2
  • .net 按比例显示图片的缩略图
  • .net 受管制代码
  • .NET成年了,然后呢?
  • .Net转前端开发-启航篇,如何定制博客园主题
  • .pings勒索病毒的威胁:如何应对.pings勒索病毒的突袭?