Hot For Coding
ExpressJS上传文件

由于项目使用NodeJS做WebServer端语言,于是需要使用ExpressJS做一个文件上传的功能

HTML代码

HTML页面和普通页面没有什么区别

upload.html

<!DOCTYPE html>
<html>
<head>
  <title>ExpressJS upload file Nicholas Lee www.qttc.net</title>
</head>
<body>

<form action="/upload" method="post" enctype="multipart/form-data">
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />
  <br />
  <input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>

JavaScript代码

upload.js

var express = require('express');

var app = express()

app.use(express.bodyParser({ keepExtensions: true, uploadDir: './uploads' }));

app.get('/', (req, res) => {
  res.sendfile(__dirname + '/upload.html')
});

app.post('/upload', function(req, res){
  console.log(req.files) // form files
  res.status(200).end()
});

app.listen(3005)

上传文件后输出

{ file:
   { fieldName: 'file',
     originalFilename: 'qttc.png',
     path: 'uploads/30997-1ai2h27.veg6.png',
     headers:
      { 'content-disposition': 'form-data; name="file"; filename="qttc.png"',
        'content-type': 'image/png' },
     ws:
      WriteStream {
        _writableState: [Object],
        writable: false,
        domain: null,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        path: 'uploads/30997-1ai2h27.veg6.png',
        fd: null,
        flags: 'w',
        mode: 438,
        start: undefined,
        autoClose: true,
        pos: undefined,
        bytesWritten: 437341,
        closed: true },
     size: 437341,
     name: 'qttc.png',
     type: 'image/png' } }

TITLE: ExpressJS上传文件

LINK: https://www.qttc.net/110_expressjs_upload_file.html

NOTE: 转载内容请注明出处