node处理上传文件

目标

  • 图片上传与展示

  • formidable的使用

  • 首先安装formidable npm install formidable

官方文档展示
淘宝的formidable链接


var formidable = require('formidable'),
    http = require('http'),
    fs = require('fs'),
    util = require('util');

http.createServer(function(req, res) {
  if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
    // parse a file upload
    var form = new formidable.IncomingForm();

    form.parse(req, function(err, fields, files) {
      res.writeHead(200, {'content-type': 'text/plain'});
      res.write('received upload:\n\n');
      res.end(util.inspect({fields: fields, files: files})); //util.inspect(object,[showHidden],[depth],[colors])是一个将任意对象转换 为字符串的方法
    });

    return;
  }
  var content = fs.readFileSync('./post2.html');

  // show a file upload form
  res.writeHead(200, {'content-type': 'text/html'});
  res.end(content);
}).listen(8080,function () {
    console.log('start form')
});

  • 以下是post2.html




    
    post2



    


node处理上传文件_第1张图片
1484652701.png

这里有用的文件,index.js post2.html,router.js,server.js, uploadHandler.js

  • uploadHandler.js
var fs = require('fs');
var querystring = require('querystring');
var formidable = require('formidable'),
    util = require('util');

function start(response,postData) {   //上传文件页面
    console.log('do post start');
    var body = fs.readFileSync('./post2.html');
    response.writeHead(200,{"Content-Type":"text/html;charset:utf-8"});
    response.write(body);
    response.end();
}
function upload(response,request) {
    console.log('do upload');
    var form = new formidable.IncomingForm();
    form.uploadDir = 'public/upload';         //新建一个默认存放图片的目录图片传到这里
    form.parse(request,function (err,fields,files) {
        response.writeHead(200, {'content-type': 'text/html'});
         fs.renameSync(files.upload.path,"temp/test.png");      //修改文件path名

        response.write('received image:
'); response.write('![](/show)') response.end() }) } function show(response) { //图片展示页 console.log('request handler show wa called'); fs.readFile("temp/test.png",function (err,file) { if (err) { response.writeHead(500,{"content-type":"text/plain"}); response.write(err+'\n'); response.end(); }else{ response.writeHead(200,{"content-type":"image/png"}); response.write(file,"binary"); //以二进制形式写进去 response.end(); } }) } exports.start = start; exports.upload = upload; exports.show = show;

访问 http://localhost/start, 是文件上传界面,上传完后地址是 http://localhost/upload 同时在同目录的public/upload里存放了所有上传的图片

你可能感兴趣的:(node处理上传文件)