zoukankan      html  css  js  c++  java
  • 夺命雷公狗---node.js---11之文件上传

    我们在做文件上传前需要用npm来安装一个插件先,

    首先打开项目所在的目录,然后按住shift键然后右键鼠标进入命令行安装formidable

    然后开始编写上传的静态页面:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>附件上传表单</h1>
        <form name="index" action="/post" method="post" enctype="multipart/form-data">
            <label>附件:<input type="file" name="fujian"></label><br /><br />
            <input type="submit" value="上传">
        </form>
    </body>
    </html>

    然后开始编写index.js文件,必须先引入刚才下载好的formidable模块

    详细代码如下所示:

    var http = require('http'),
        fs = require('fs'),
        url = require('url'),
        util = require('util'),
        formidable = require('formidable'),
        querystring = require('querystring');
    var server = http.createServer(function(req,res){
        var pathname = url.parse(req.url).pathname;
        if(pathname == '/index'){
            var pageContent = fs.readFile('index.html','utf-8',function(err,data){
                if(err){
                    console.log('Server error:111');
                }else{
                    res.writeHead(200,{"Content-Type":"text/html"});
                    res.write(data);
                    res.end();
                }
            });
        }else if(pathname == '/post'){
            var form = new formidable.IncomingForm();
            form.uploadDir = './temp';
            form.parse(req,function(err,fields,files){
                res.writeHead(200,{"Content-Type":"text/html"});
                console.log(files);//看下文件上传信息
                var path = files.fujian.path;
                var timestamp = (new Date()).valueOf(); //生成时间戳,然后在下面用时间戳给图片命名
                fs.rename(files.fujian.path,"./temp/"+timestamp+'.jpg');//这里的temp目标必须提前准备好,不然报错
                res.end();
            });
        }else{
            res.writeHead(404,{"Content-Type":"text/plain"});
            res.end('error:404');
            console.log('error');
        }
    });
    server.listen(3323);
    console.log('@http://localhost:3323');

    然后进行测试。。。

    这样我们即可成功完成上传功能....

  • 相关阅读:
    新安装的Apache和php,测试可以解析phpinfo,但是无法打开drupal网站
    Drupal7安装注意事项
    drupal7 为视图添加 过滤标准 内容类型
    Drupal网站报错:PDOException: in lock_may_be_available()
    窗口聚合函数与分组聚合函数的异同
    Linux环境下段错误的产生原因及调试方法小结(转)
    gzip 所使用压缩算法的基本原理(选摘)
    InfluxDB使用纪录
    子网掩码解释(转)
    列存的压缩原理学习
  • 原文地址:https://www.cnblogs.com/leigood/p/5769425.html
Copyright © 2011-2022 走看看