Reputation: 1
I am currently using multer to submit a profile picture to the folder "pfps" for a school assignment, which should create a file that is the same as the front-end. However, it creates a file of random text characters with no .png or .jpg ending tag and cannot be read.
My code in the backend javascript currently is
const express = require("express");
const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database(".database/user.db")
var fs = require('fs');
const cors = require("cors");
var bodyParser = require('body-parser');
const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'myPWA/pfps')
},
filenane: (req, file, cb) => {
console.log(file);
cb(null, Date.now() + path.extname(file.originalname))
}
})
const upload = multer({ dest: "/pfps" });
const app = express();
app.use(express.static(path.join(__dirname, "myPWA")));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "myPWA/index.html"));
});
app.use(cors());
app.use(express.json());
app.use(
bodyParser.urlencoded({
extended: true
}),
express.static(path.join(__dirname, "myPWA"))
)
app.post('/profile', upload.single('avatar'), function (req, res) {
console.log(req.body);
console.log(req.files);
})
and the html for the form is
<div class="page-content">
<form action="/profile" method="post" enctype="multipart/form-data">
<input type="file" name="avatar" id="avatar"/>
<button type="submit">upload</button>
</form>
</div>
Which should return some file in the backend files like this However, it returns a file like this.
Also, when I tried to log the file,
console.log(req.body);
console.log(req.files);
it returns
[Object: null prototype] {}
undefined
however I have looked online and it returns something like this
Does anybody have a solution?? Thanks in advance.
Upvotes: 0
Views: 37
Reputation: 3
It might be because of the typo in your backend:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'myPWA/pfps')
},
filenane: (req, file, cb) => {
console.log(file);
cb(null, Date.now() + path.extname(file.originalname))
}
})
correct "filenane" to "filename".
Hope it helps.
Upvotes: 0