安装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. 【JMeter4.0】之 “jdk1.8、JMeter4.0” 安装与配置以及JMeter永久汉化和更改界面背景、并附加附录:个人学习总结

    目录: 一.首先,需要安装.配置jdk 二.其次,安装.配置JMeter 三.JMeter汉化以及更改界面背景 四.附录:个人学习总结 一.首先,需要安装.配置jdk   返回目录 1.到官网下载1. ...

  2. phpstudy配置php7.1.11 + phpstudy nginx伪静态

    切记要把新的php版本配到环境变量,cmd才会生效 php7.1.11下载地址 http://windows.php.net/download/ 下载之后,解压. 重名的为php-7.1.11-nts ...

  3. c语言三元组

    // Triplet.cpp : 定义控制台应用程序的入口点.//#include "stdio.h"#include "stdlib.h"#define OK ...

  4. 大组合取模之:1<=n<=m<=1e6,1<=p<=1e9

    /****************************** 大组合取模之:1<=n<=m<=1e6,1<=p<=1e9 使用:程序最开始调用getprime(),需要 ...

  5. Stacks of Flapjacks(栈)

     Stacks of Flapjacks  Background Stacks and Queues are often considered the bread and butter of data ...

  6. ElasticSearch(二十一)正排和倒排索引

    1.区别 搜索的时候,要依靠倒排索引:排序的时候,需要依靠正排索引,看到每个document的每个field,然后进行排序,所谓的正排索引,其实就是doc values 在建立索引的时候,一方面会建立 ...

  7. [luogu4315]月下“毛景树”

    [luogu4315]月下"毛景树" luogu 联赛前复习一发树剖.不会告诉你WA了4发 #define ls x<<1,l,mid #define rs x< ...

  8. Python中pymysql模块详解

    安装 pip install pymysql 使用操作 执行SQL #!/usr/bin/env pytho # -*- coding:utf-8 -*- import pymysql # 创建连接 ...

  9. 我的Android进阶之旅------>关于android:layout_weight属性的一个面试题

    最近碰到一个面试题,按照下图,由Button和EditText组成的界面下厨布局代码,解决这题目需要使用android:layout_weight的知识. 首先分析上图所示的界面可以看成一下3个部分. ...

  10. date_default_timezone_get():

    [Symfony\Component\Debug\Exception\ContextErrorException]                      Warning: date_default ...