• node-实现文件上传功能
  • 发布于 2个月前
  • 82 热度
    0 评论
  • 钟子龙
  • 0 粉丝 6 篇博客
  •   

今天要用node.js实现一个文件上传的功能,话不多说先看文件的目录结构


router.js
function route(handle, pathname, response, request) {
  console.log('about to route a request for ' + pathname)
  if (typeof handle[pathname] === 'function') {
    return handle[pathname](response, request)
  } else {
    console.log('No request handler found for ' + pathname)
    response.writeHead(400, { 'Content-Type': 'text/plain' })
    response.write('404 Not found')
    response.end()
  }
}
exports.route = route
在路由中设置404 页面,根据index.js 的路由来匹配的时候,比较好判断用户访问的页面是否存在。然后根据路由匹配跳转到对于的页面中。
可以看看index.js
/**
 * 实现大文件上传
 * 用户上传图片,并且在浏览器中显示
 */
var server = require('./server.js')
var router = require('../router.js')
var requestHandlers = require('./requestHandler.js')

console.log(router)
var handle = {}
handle['/'] = requestHandlers.start
handle['/start'] = requestHandlers.start
handle['/upload'] = requestHandlers.upload
handle['/show'] = requestHandlers.show
server.start(router.route, handle)  //启动服务
requestHandlers.js 就是对应不同路由,拿到不同的处理方法。
var querystring = require('querystring')
var fs = require('fs')
formidable = require('formidable')
function start(response) {
  console.log("Request handler 'start' was called.")
  var body =
    '<html>' +
    '<head>' +
    '<meta http-equiv="Content-Type" content="text/html; ' +
    'charset=UTF-8" />' +
    '</head>' +
    '<body>' +
    '<form action="/upload" enctype="multipart/form-data" ' +
    'method="post">' +
    '<input type="file" name="upload" multiple="multiple">' +
    '<input type="submit" value="Upload file" />' +
    '</form>' +
    '</body>' +
    '</html>'
  response.writeHead(200, { 'Content-Type': 'text/html' })
  response.write(body)
  response.end()
}
function upload(response, request) {
  console.log("Request handler 'upload' was called.")

  var form = new formidable.IncomingForm()
  console.log('about to parse')
  form.parse(request, function(error, fields, files) {
    console.log('parsing done')
    console.log(fields)
    console.log(files)
    fs.renameSync(files.upload.path, '/tmp/test.png')
    response.writeHead(200, { 'Content-Type': 'text/html' })
    response.write('received image:<br/>')
    response.write("<img src='/show' />")
    response.end()
  })
}
function show(response) {
  console.log("Request handler 'show' was called.")
  fs.readFile('/tmp/test.png', 'binary', function(error, file) {
    if (error) {
      response.writeHead(500, { 'Content-Type': 'text/plain' })
      response.write(error + '\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
requestHandlers.start  =>  默认页面
requestHandlers.upload =>  上传图片
使用第三包:formidable是一个用于处理文件、图片、视频等数据上传的模块,支持GB级上传数据处理,支持多种客户端数据提交。有极高的测试覆盖率,非常适合在生产环境中使用。
requestHandlers.show => 用于显示图片。
fs.readFild('/tmp/test.png') 暂时存在的普片的名称。

最后介绍一下server.js
var http = require('http')
var url = require('url')
/**
 * formidable 模块了,使用外部模块与内部模块类似
 */
var formidable = require('formidable')
var sys = require('sys')
function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname
    console.log('Request for ' + pathname + ' received.')
    route(handle, pathname, response, request)
  }
  http.createServer(onRequest).listen(8888)
  console.log('Server has started.')
}
exports.start = start
最后node index.js 整个项目就跑起来,大家试试哈~~~
用户评论