У меня проблема с загрузкой изображения из файла ввода в базу данных. Фронтенд, использующий реагировать на редукс-форму и сервер node js mongodb. Я тестировал в почтальоне, он работает правильно , но когда я выкладываю через приложение, выдает ошибку. Вот мой код:
DestinationForm. js (React)
import React from "react";
import FileInput from "../FileInput";
class DestinationForm extends React.Component {
renderInput = ({ input, label, meta, type, className }) => {
const nameOfClass = `field ${meta.error && meta.touched ? "error" : ""}`;
return (
<div className={nameOfClass}>
<label>{label}</label>
<input className={className} {...input} autoComplete="off" type={type} />
{this.renderError(meta)}
</div>
);
};
onSubmit = formValues => {
this.props.onSubmit(formValues);
console.log(formValues);
};
render() {
return (
<div>
<form onSubmit={this.props.handleSubmit(this.onSubmit)} encType="multipart/form-data">
<Field name="name" component={this.renderInput} label="Destination Name" type="text" />
<Field name="image" label="Image" component={FileInput} />
<button type="submit">Submit</button>
</form>
</div>
);
}
}
FileInput. js (React)
import React from "react";
const handleChange = handler => ({ target: { files } }) =>
handler(files.length ? { file: files[0], name: files[0].name } : {});
export default ({
input: { onChange, onBlur, value: omitValue, ...inputProps },
meta: omitMeta,
...props
}) => (
<input
type="file"
onChange={handleChange(onChange)}
onBlur={handleChange(onBlur)}
{...inputProps}
{...props}
/>
);
адресатов. js (сервер, node js)
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, "./public/images/uploads/");
},
filename: function(req, file, cb) {
cb(null, new Date().toISOString() + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
cb(null, true);
} else {
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
router.post("/", upload.single("image"), async (req, res) => {
try {
const { name, description, city, category, lat, lang } = req.body;
const image = req.file.path;
let newDestination = {
name,
image
};
newDestination = await Destination.create(newDestination);
res.json(newDestination);
} catch (err) {
console.log(err);
res.status(500).send("Something went wrong");
}
});
Я использую тип Строка в изображение в пн goose.
консоль .log (FormValues) при отправке (это в DestinationForm. js)
{name: "hello", image: {…}, description: "world"}
name: "hello"
image:
file: File {name: "20181109113259_save.jpg", lastModified: 1541747174000,
lastModifiedDate:
Fri Nov 09 2018 14:06:14 GMT+0700 (Western Indonesia Time), webkitRelativePath: "", size:
893152, …}
name: "20181109113259_save.jpg"
__proto__: Object
__proto__: Object
xhr.js:178 POST http://localhost:5000/api/destinations 500 (Internal Server Error)
Почтальон работает правильно
{
"comments": [],
"_id": "5e7b515d81bac0139960fce3",
"name": "meoong",
"image": "public/images/uploads/2020-03-25T12:41:01.063Z20190114_190634.jpg"
"__v": 0
}
Извините за мой плохо Engli sh ? спасибо