NodeJS 文件上传

Source

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.

12334242-414d90f7c0b0e5da.gif
upload_file.gif

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

12334242-802726e8f9b609b7.png
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

12334242-270efbdb0a5e429d.gif
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