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');

    然后进行测试。。。

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

  • 相关阅读:
    POJ 1659 Frogs' Neighborhood
    zoj 2913 Bus Pass(BFS)
    ZOJ 1008 Gnome Tetravex(DFS)
    POJ 1562 Oil Deposits (DFS)
    zoj 2165 Red and Black (DFs)poj 1979
    hdu 3954 Level up
    sgu 249 Matrix
    hdu 4417 Super Mario
    SPOJ (BNUOJ) LCM Sum
    hdu 2665 Kth number 划分树
  • 原文地址:https://www.cnblogs.com/leigood/p/5769425.html
Copyright © 2011-2022 走看看