NodeJS 文件上传

2019-01-10  本文已影响0人  不知道的是

keywords

  1. multipart/form-data
  2. HTML entity

各依赖功能描述

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

上一篇 下一篇

猜你喜欢

热点阅读