ExpressJS上传文件

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

HTML代码

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

【国内直连ChatGPT 29元起】
国内直连ChatGPT,Plus会员每月29元起,支持最新o1模型探索更多领域,无需注册OpenAI账号。

upload.html

<!DOCTYPE html>
<html>
<head>
  <title>ExpressJS upload file 琼台博客 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: 原创内容,转载请注明出自琼台博客