美文网首页
NodeJS 文件上传

NodeJS 文件上传

作者: 不知道的是 | 来源:发表于2019-01-10 10:20 被阅读0次

    keywords

    1. multipart/form-data
    2. HTML entity

    各依赖功能描述

    • formidable
      A Node.js module for parsing form data, especially file uploads.

    • html-entities
      Fast html entities library.

    upload_file.gif

    files.filetoupload.name 如果用户上传的文件名称中包含汉字等字符则会被转换为 HTML 字符实体(在做上传文件永久存储的时候通过 html-entities 将 HTML entity 转换回汉字即可)

    image.png
    // app.js
    const http = require('http')
    const formidable = require('formidable')
    const fs = require('fs')
    // https://www.npmjs.com/package/html-entities
    const Entities = require('html-entities').XmlEntities
    const entities = new Entities()
    const port = 8080
    
    http.createServer((req, res) => {
      if (req.url == '/fileupload') {
        const form = new formidable.IncomingForm()
        form.parse(req, (err, fields, files) => {
          // console.log(files)
          const oldpath = files.filetoupload.path
          const newpath = 'C:/Users/lulu/' + entities.decode(files.filetoupload.name)
          fs.rename(oldpath, newpath, err => {
            if (err) throw err
            res.write('File uploaded and moved!')
            res.end()
          })
        })
      } else {
        res.writeHead(200, { 'Content-Type': 'text/html' })
        res.write('<form action="fileupload" method="post" enctype="multipart/form-data">')
        res.write('<input type="file" name="filetoupload"><br>')
        res.write('<input type="submit">')
        res.write('</form>')
        return res.end()
      }
    }).listen(port, () => {
      console.log(`http://localhost:${port}`)
    })
    

    HTML entity encode/decode

    HTML entity encode_decode.gif

    https://www.w3schools.com/nodejs/nodejs_uploadfiles.asp
    https://mothereff.in/html-entities
    https://www.npmjs.com/package/html-entities
    https://blog.teamtreehouse.com/uploading-files-ajax
    https://www.npmjs.com/package/formidable

    相关文章

      网友评论

          本文标题:NodeJS 文件上传

          本文链接:https://www.haomeiwen.com/subject/ymeorqtx.html