'How to insert related ID along a picture in picture upload component in Reactjs?
I have an upload component, and while trying to upload a picture into my database I'm also trying to insert the related trip id (as tripId) which is necessary for my one-to-many relationship between pictures and trips. While the picture is inserting into the database fine and getting into the right folder, the trip id never goes into the picture table. I don't understand where the error comes from and how to solve it.
I am using NodeJs, Sequelize and multer for my picture upload.
Below is the code for my upload component, I am passing the tripId to the component through props and thanks to console.log(form.getAll("tripId")), I can see in the console that it is indeed getting the right ID.
export default function Upload(props) {
const [selectedFile, setSelectedFile] = useState("");
// On file select (from the pop up)
const onFileChange = (event) => {
// Update the state
setSelectedFile(event.target.files[0]);
};
// On file upload (click the upload button)
const onFileUpload = () => {
// Create an object of formData
const form = new FormData();
const tripId = props.tripId;
console.log(tripId);
// Update the formData object
form.append("file", selectedFile, selectedFile.name);
form.append("tripId", tripId);
console.log(form.getAll("tripId"));
// Details of the uploaded file
console.log("selected file", selectedFile);
console.log("selected file name", selectedFile.name);
// Request made to the backend api
// Send formData object
axios({
method: "post",
url: "http://localhost:8080/api/upload/upload",
data: form,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
};
}
Here is my upload middleware :
const util = require("util");
const multer = require("multer");
const maxSize = 2 * 1024 * 1024;
const { uuid } = require("uuidv4");
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/public/images/");
},
filename: (req, file, cb) => {
file.originalname = uuid() + ".png";
console.log(file.originalname + "toto");
cb(null, file.originalname, req);
},
});
let uploadFile = multer({
storage: storage,
limits: { fileSize: maxSize },
}).single("file");
let uploadFileMiddleware = util.promisify(uploadFile);
module.exports = uploadFileMiddleware;
Here is my upload controller :
const uploadFile = require("../middleware/upload");
const fs = require("fs");
const db = require("../models");
const Picture = db.picture;
const upload = async (req, res) => {
try {
console.log("test upload");
await uploadFile(req, res);
if (req.file == undefined) {
console.log("erreur");
return res.status(400).send({ message: "Please upload a file!" });
}
Picture.create({
tripId: req.body.tripId,
path: "/public/images/" + req.file.originalname,
});
res.status(200).send({
message: "Uploaded the file successfully: " + req.file.originalname,
});
} catch (err) {
res.status(500).send({
message: `Could not upload the file: ${req.file.originalname}. ${err}`,
});
}
};
const getListFiles = (req, res) => {
const directoryPath = __basedir + "/public/images/";
fs.readdir(directoryPath, function (err, files) {
if (err) {
res.status(500).send({
message: "Unable to scan files!",
});
}
let fileInfos = [];
files.forEach((file) => {
fileInfos.push({
name: file,
url: "http://localhost:8080/public/images/" + file,
});
});
res.status(200).send(fileInfos);
});
};
const download = (req, res) => {
const fileName = req.params.name;
const directoryPath = __basedir + "/public/images/";
res.download(directoryPath + fileName, fileName, (err) => {
if (err) {
res.status(500).send({
message: "Could not download the file. " + err,
});
}
});
};
module.exports = {
upload,
getListFiles,
download,
};
Here is my picture model :
module.exports = (sequelize, DataTypes) => {
const Picture = sequelize.define("picture", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
path: {
type: DataTypes.STRING,
allowNull: false,
},
tripId: {
type: DataTypes.INTEGER,
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
},
});
return Picture;
};
And finally here is how I joined the tables in my index.js :
//Pictures belong to Trips
db.trips.hasMany(db.picture, { as: "pictures" });
db.picture.belongsTo(
db.trips,
{ foreignKey: "tripId", as: "trip" },
{ onDelete: "CASCADE" }
);
Thanks in advance for the help.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
