У меня есть форма с кнопкой, которая позволяет мне выбрать файл, затем я отправляю форму с этой информацией:
address_line1,
address_line2,
locality,
region,
postcode
Я пытаюсь сохранить файл с именем, которое я получаю из вставить в бэкэнд, который называется id_property или по умолчанию, чтобы хотя бы сохранить файл с address_line1 из формы, когда они отправляются вместе, я пробовал это в бэкэнде:
//this is the routes.js:
const storage = multer.diskStorage({
destination: "public/properties",
filename: (_req, file, cb) => {
const { address_line1 } = req.body;
const ext = file.originalname.slice(file.originalname.lastIndexOf("."));
cb(null, address_line1 + ext); // cb stands for call back
}
});
const upload = multer({ storage }).single("photo_property"); //TODO mirar como subir varias fotos
router.post("/register", upload, propertiesController.register);
//this is the controller.js
propertiesController.register = (request, response) => {
var photo_property;
const token = request.headers.authorization.replace("Bearer ", "");
if (request.file) {
photo_property = request.file.filename;
} else {
photo_property = "";
}
jwt.verify(token, myprivatekey);
const { id_user } = jwtDecode(token, myprivatekey);
// const photo_property = request.file.filename;
const {
address_line1,
address_line2,
locality,
region,
postcode
} = request.body;
connection.query(
`INSERT INTO property (id_user, address_line1, address_line2, locality ,region , postcode, photo_property)
VALUES ('${id_user}', '${address_line1}', '${address_line2}', '${locality}', '${region}','${postcode}', '${photo_property}') `,
(err, results) => {
console.log(results);
if (err) {
response.sendStatus(400);
console.log(err);
} else {
connection.query(
`SELECT * FROM property WHERE id_property = ${results.insertId}`,
(err, results2) => {
if (err) {
response.sendStatus(400);
console.log(err);
}
response.send(results2[0]);
}
);
}
}
);
};
и это где я получаю данные:
async sendForm() {
const token = localStorage.getItem("token");
if (this.inputPhoto_propertyeRef.current?.files) {
var photo_property = this.inputPhoto_propertyeRef.current.files[0];
const formData = new FormData();
let {
address_line1,
address_line2,
locality,
region,
postcode
} = this.state;
postcode = String(postcode);
formData.append("photo_property", photo_property);
formData.append("address_line1", address_line1);
formData.append("address_line2", address_line2);
formData.append("locality", locality);
formData.append("region", region);
formData.append("postcode", postcode);
const property = await addProperty(token, formData);
this.props.addOneProperty(property);
this.props.toggleForm();// function coming from the paren which dismount the component after sending
}
}
что мне нужно добавить в multer и / или в контроллере, чтобы сделать это ???