0

I was trying multer for the first time and I got confused on how to upload the selected file. I successfully set up my connection to the backend using ajax and the things I'm confused about are

  1. Am I assigning the file input data to send to the back end correctly? I am getting the raw value output of the input file element and sending it to the backend currently. Is that the right way?
  2. When calling the multer upload function on my backend alongside calling app.post, what does the "myFile" represent in upload.single('myFile') currently I'm assuming it is the fileName sent from the client-side. Is that right?
  3. And last how do I assign a specific directory to save the uploaded file in fs? Any help is appreciated. Thanks in advance.
const express = require('express');
const multer = require("multer")
const path = require('path');
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
const port = process.env.PORT || 3000
var cors = require('cors');

app.use(cors());
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.listen(port, () => {
  console.log('Server is up on port ' + port);
})

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "uploads/")
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + "-" + file.originalname)
  },
})

const uploadStorage = multer({
  storage: storage
})

app.post('/uploadImage', upload.single('myFile'), (req, res, next) => {
  try {
    res.send(req.body);
    console.log(req.body.chooseFileValue)
  } catch (error) {
    console.log(error);
    res.send(400);
  }
})
<!DOCTYPE html>
<html lang="en">

<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">

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

</head>

<body>
  <h1>Single File Upload Demo</h1>

  <form name="mainForm" action="/uploadProfilePicture" enctype="multipart/form-data" method="POST">

    <span>Upload Profile Picture:</span>
    <input type="file" name="mypic" id="chooseFile" required /> <br>
    <button type="button" class="uploadBtn" id="uploadBtn">Upload</button>
  </form>

  <script>
    var chooseFile = document.getElementById('chooseFile')
    $('#uploadBtn').click(function() {
      console.log(chooseFile.value)
      $.ajax({
        url: 'http://localhost:3000/uploadImage',
        type: 'POST',
        "crossDomain": true,
        headers: {
          "accept": "application/json",
          "Access-Control-Allow-Origin": "*"
        },
        cache: false,
        data: {
          "chooseFileValue": chooseFile.value
        },
        success: function(data) {
          console.log(data)
        },
        error: function(jqXHR, textStatus, err) {
          alert('text status ' + textStatus + ', err ' + err)
        }
      })
    });
  </script>
</body>

</html>
Phil
  • 157,677
  • 23
  • 242
  • 245
seriously
  • 1,202
  • 5
  • 23
  • There are several problems here. First, see [this answer](https://stackoverflow.com/a/24939229/283366) from the duplicate for how to upload files via jQuery's `$.ajax()`. You are also doubling up on CORS config. I suggest only using the `cors` middleware. If you're still running into problems after that, please [update the code in your question](https://stackoverflow.com/posts/69969106/edit) to match what you're currently working with – Phil Nov 15 '21 at 03:24
  • @Phil do you know the answer to my second question by any chance? – seriously Nov 15 '21 at 03:27
  • The string used in `single()` is the name of the `FormData` field you add for your file. If you add `formData.append("myFile", chooseFile.files[0])` on the client side, you use `upload.single("myFile")` on the server side – Phil Nov 15 '21 at 03:33
  • Also, `upload.single()` should be `uploadStorage.single()` in your Express app. I strongly suggest you read the [Multer documentation](https://github.com/expressjs/multer#readme) carefully – Phil Nov 15 '21 at 03:34
  • When you refered to chooseFile in ```formData.append("myFile", chooseFile.files[0])``` does that reference the inputBar it self or the form group? – seriously Nov 15 '21 at 03:36
  • The same one as in your question's code... `var chooseFile = document.getElementById('chooseFile')` – Phil Nov 15 '21 at 03:37
  • got it thanks @Phil – seriously Nov 15 '21 at 03:38

0 Answers0