安装npm install formidable

先把文件上传到临时文件夹,再通过fs重命名移动到指定的目录即可

fs.rename即重命名,但是fs.rename不能夸磁盘移动文件,所以我们需要指定上传的临时目录要和最终目录在同一磁盘下

前段请求

方法1:使用form标签和submit提交

     form(action='/uploadImg', method="post", enctype="multipart/form-data" )
         input(type="file", id="file1", name="file1")
         br
         button(type="submit", id="bt1", name="bt1") upload

方法2:ajax,post提交

    input(type="file", id="file1", name="file1")

button(id="upload", name="upload") submit

javascript方法

    $("#upload").click(function(){

      var data = new FormData();

      var files = $("#file1")[0].files;

      if(files){

        data.append("file", files[0]);

      }

      $.ajax({

        type: 'post',

        dataType: 'json',

        url:'/uploadImg',

        data : data,

        contentType: false,

        processData: false,

        success : function () {}

      }    

上传实现方法:form解析后的files是个对象,所以可以实现多文件上传

tool.uploadImg =function(req, res){
    var fs = require('fs');
    var formidable = require("formidable");
    var form = new formidable.IncomingForm();
    form.uploadDir = "./public/upload/temp/";//改变临时目录
    form.parse(req, function(error, fields, files){
        for(var key in files){
            var file = files[key];
            var fName = (new Date()).getTime();
            switch (file.type){
                case "image/jpeg":
                    fName = fName + ".jpg";
                    break;
                case "image/png":
                    fName = fName + ".png";
                    break;
                default :
                    fName =fName + ".png";
                    break;
            }
            console.log(file.size);
            var uploadDir = "./public/upload/" + fName;
            fs.rename(file.path, uploadDir, function(err) {
                if (err) {
                    res.write(err+"\n");
                    res.end();
                }
                res.write("upload image:<br/>");
                res.write("<img src='/imgShow?id=" + fName + "' />");
                res.end();
            });
        }
    });
};

显示上传后的文件

tool.imgShow = function(req, res){
    var fs = require("fs");
    var arg = tool.handleGetArg(req, res);
    var uploadDir = "./public/upload/" + arg["id"];
    fs.readFile(uploadDir, "binary", function(err, file){
        if(err){
            res.write(err+"\n");
            res.end();
        }else{
            res.write(file, "binary");
            res.end();
        }
    });
};

node.js+express+jade系列六:图片的上传的更多相关文章

  1. node.js+express+jade系列七:富文本编辑框的使用

    下载nicEdit富文本编辑框, 把nicEdit.js文件放到public/javascripts/下 新建jade文件:代码如下 doctype htmlhtml    head        t ...

  2. node.js+express+jade系列五:ajax登录

    本文通过jquery实现简单的无刷新登录 1:首先要在router中配置登录请求,因为登录需要传user和pwd考虑到安全需用post请求 {        path:'/',        meth ...

  3. node.js+express+jade系列四:jade嵌套的使用

    jade是express自带的模板引擎 jade文件可以嵌套使用,include引用外部jade文件,extends引用jade模板 例如 有一个主jade文件layout.jade,引用top.ja ...

  4. node.js+express+jade系列三:404错误的配置

    1:新建一个404.jade 2:在app.js后面配置如下代码 app.use(function(req, res){        res.render("404", {sta ...

  5. node.js+express+jade系列二:rotue路由的配置

    页面的访问最常见的是get和post两种,无论是get请求还是post请求express自动判断执行app.get或app.post 1:app.get(名称,路径)或app["get&qu ...

  6. node.js+express+jade系列一:session的使用

    此出只介绍内存session的配置好使用 1:打开app.js文件,添加下面红色内容,一定要注意位置在router前面 app.use(express.methodOverride()); sessi ...

  7. node.js系列(实例):原生node.js+formidable模块实现简单的文件上传

    /** * 原生node.js结合formidable模块实现图片上传改名 * @Author:Ghost * @Date:2016/07/15 * @description: * 1.引入模块htt ...

  8. [译]简单得不得了的教程-一步一步用 NODE.JS, EXPRESS, JADE, MONGODB 搭建一个网站

    原文: http://cwbuecheler.com/web/tutorials/2013/node-express-mongo/ 原文的源代码在此 太多的教程教你些一个Hello, World!了, ...

  9. node.js:《接口实现文件的上传和下载》

    使用node.js写上传文件和下载文件的接口 上传接口: 开始写接口前,我们先安装一个上传文件的插件:npm install multer 安装成功在package.json或package-lock ...

随机推荐

  1. 微软2016校园招聘在线笔试第二场 题目1 : Lucky Substrings

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 A string s is LUCKY if and only if the number of different ch ...

  2. selenium驱动Firefox跳转页慢慢慢的问题(待验证)

    转载至http://www.cnblogs.com/yicaifeitian/p/5198871.html 为了解决这个问题,我是查了很多资料,解决方案是百度出来的.抱歉,我忘记出处在哪了,代码如下: ...

  3. web安全之SQL注入---第二章 什么是sql注入?

    如何理解SQL注入?SQL注入是一种将SQL代码添加到输入参数中传递到SQL服务器解析并执行的一种攻击方法总结:其实就是输入的参数没有进行过滤,直接参加sql语句的运算,达到不可预想的结果.SQL注入 ...

  4. Configure the modules to be find by modprobe

    sudo ln -s /path/to/module.ko /lib/modules/`uname -r` sudo depmod -a #depmod will output a dependenc ...

  5. 自定义circleindicator

    在此申明,并不是自己写的,只是为了方便日后使用 我使用的circleindicator是从大神的gitHub中弄来的, 使用如下: 一.在配置中导入 compile 'me.relex:circlei ...

  6. ASIHTTPRequest数据压缩

    本文转载至  http://blog.csdn.net/zhuoyuetec/article/details/18216439 IOSASIHttprequestsetShouldCompressRe ...

  7. iOS GPUImage 滤镜介绍

    这里直接引用官方描述: The GPUImage framework is a BSD-licensed iOS library that lets you apply GPU-accelerated ...

  8. zabbix server 端安装

    1.系统环境 [root@crazy-acong ~]# cat /etc/redhat-release CentOS release 6.6 (Final) [root@crazy-acong ~] ...

  9. redis持久化RDB详细操作步骤

    1.xshell远程登录服务器ssh root@192.168.142.130 2.切换到redis目录 3.创建一个配置文件s2-redis.conf 4.编辑文件 vi s2-redis.conf ...

  10. linux c编程:线程创建

    前面章节中介绍了进程.从这一章开始介绍线程.进程和线程的差别是什么呢: 进程是具有一定独立功能的程序关于某个数据集合上的一次运行活动,进程是系统进行资源分配和调度的一个独立单位.  线程是进程的一个实 ...