

以下のサイトを見ながらexpress上でexpress-form-dataを使用してファイルのアップロードを実装しました。

[Express.js ファイルアップロード (express-form-data
編)](https://qiita.com/tadnakam/items/4f7af58af86cf60bf0e8)

しかし、実行結果（router.jsのconsole.logの結果）のように何も表示されずファイルの受け渡しができていません。  
どのようにすればファイルのアップロードをできるようになるか教えてほしいです。

実行結果  
[![画像の説明をここに入力](https://i.stack.imgur.com/Q354t.png)](https://i.stack.imgur.com/Q354t.png)

ディレクトリ構成  
[![画像の説明をここに入力](https://i.stack.imgur.com/VGTYV.png)](https://i.stack.imgur.com/VGTYV.png)

ソースコード  
app.js

[code]

    var functions = require('firebase-functions');
    var createError = require('http-errors');
    var express = require('express');
    var path = require('path');
    var cookieParser = require('cookie-parser');
    var logger = require('morgan');
    var admin = require('firebase-admin');
    admin.initializeApp();
    var app = express();
    
    
    // view engine setup
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.set('admin', admin.firestore().collection('users'));
    app.set('recipe', admin.firestore().collection('recipe'));
    app.set('bucket',admin.storage().bucket())
    app.use(logger('dev'));
    app.use(express.json());
    app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));
    
    
    // router
    app.use('/', require('./routes'));
    // images
    app.use(express.static('./public/images'));
    
    // catch 404 and forward to error handler
    app.use(function(req, res, next) {
      next(createError(404));
    });
    
    // error handler
    app.use(function(err, req, res, next) {
      // set locals, only providing error in development
      res.locals.message = err.message;
      res.locals.error = req.app.get('env') === 'development' ? err : {};
    
      // render the error page
      res.status(err.status || 500);
      res.render('error');
    });
    
    exports.app = functions.https.onRequest(app);
    
[/code]

index.js

[code]

    var express = require('express');
    var router = express.Router();
    
    router.get('/', function(req, res, next) {
      res.send("test")
    });
    
    router.use('/result',require('./result'))
    module.exports = router;
    
[/code]

result.js

[code]

    var express = require('express');
    var router = express.Router();
    
    const path = require("path")
    const formData = require('express-form-data');
    router.use(formData.parse({uploadDir:path.join(__dirname,'upload'), autoClean:true}));
    router.use(formData.format());
    /* GET home page. */
    router.get('/', function(req, res, next) {  
      res.render('index', {
        title: "test",
      })
    });
    
    router.post('/', (req, res) => {
      console.log("aaa")
      console.log("aaa"+req.files.file1.name)
      res.redirect("/")
    });
    module.exports = router;
    
[/code]

index.ejs

[code]

    <!DOCTYPE html>
    <html lang="jp">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title><%=title%></title>
    </head>
        <body>
            <form id="form1" method="POST" enctype="multipart/form-data">
                <fieldset class="form-group">
                    <label for="file1">アップロードファイル </label>
                    <input type="file" id="file1" name="file1" class="form-control" />
                </fieldset>
                <fieldset class="form-group">
                    <input type="button" class="btn btn-primary" value=" 送信 " onclick="javascript:submitClick()" />
                </fieldset>
                <br />
            </form>
            <br />
    
            <script>
                function element(id) {
                    return document.getElementById(id);
                }
    
                function submitClick() {
                    const formData = new FormData(form1);
                    fetch('/result', {method:"POST", body:formData})
                    .then(res => res.text())
                    .then(text => element('message').innerText = text)
                    .catch(err => element('message').innerHTML = err.message);
                }
            </script>
        </body>
    </html>
    
[/code]

package.json

[code]

    {
      "name": "functions",
      "version": "0.0.0",
      "private": true,
      "scripts": {
        "serve": "firebase emulators:start --only functions",
        "shell": "firebase functions:shell",
        "start": "npm run shell",
        "deploy": "firebase deploy --only functions",
        "logs": "firebase functions:log"
      },
      "engines": {
        "node": "18"
      },
      "dependencies": {
        "axios": "^1.4.0",
        "cookie-parser": "~1.4.4",
        "crypto": "^1.0.1",
        "debug": "~2.6.9",
        "dotenv": "^16.3.1",
        "ejs": "^3.1.9",
        "express": "^4.18.2",
        "express-form-data": "^2.0.22",
        "firebase-admin": "^11.8.0",
        "firebase-functions": "^4.3.1",
        "googleapis": "^118.0.0",
        "http-errors": "~1.6.3",
        "morgan": "~1.9.1",
        "openai": "^3.3.0",
        "util": "^0.12.5"
      }
    }
    
[/code]


CC BY-SA 4.0
2023-07-08T10:03:28.967
95528
2023-07-09T05:11:22.603
2023-07-09T05:11:22.603
3060
54696
question
express.js
express上（express-generator）でファイルのアップロードができません