#mysql #node.js #reactjs #file-upload #multer
Вопрос:
Я пытаюсь сохранить фотографию в своей базе данных. Я внедрил multer
промежуточное программное обеспечение для загрузки файла на свой сервер. У меня есть папка под названием «Загрузки», в которой я храню свою фотографию. Я успешно переименовал файл в своем бэкэнде с расширением, и я могу получить файл в папке «Загрузки». Однако проблема, с которой я сейчас сталкиваюсь, заключается в сохранении имени файла/ пути к файлу в базе данных mysql, чтобы я мог снова получить его в своем интерфейсе.
editUser.js (форма переднего плана):
import axios from "axios"; import { React, useState, useEffect } from "react"; import { useHistory, withRouter } from "react-router-dom"; function UserMaster_Edit(props) { const [CmpnyCode, setCmpnyCode] = useState(""); const [UserID, setUserID] = useState(""); const [UserFullName, setUserFullName] = useState(""); const [UserDetail, setUserDetail] = useState(""); const [LoginID, setLoginID] = useState(""); const [Password, setPassword] = useState(""); const [UserPin, setUserPin] = useState(""); const [UserEmailID, setUserEmailID] = useState(""); const [UserFP, setUserFP] = useState({}); const [Photo, setPhoto] = useState({}); const [IsActive, setIsActive] = useState(""); const [LicCount, setLicCount] = useState(""); const [DateCreated, setDateCreated] = useState(""); const [CreatedBy, setCreatedBy] = useState(""); const [RecordChanged, setRecordChanged] = useState(""); const [LocationID, setLocationID] = useState(""); const [isValid, setisValid] = useState(""); const [isDeleted, setisDeleted] = useState(""); const history = useHistory(); const argu = props.match.params.UserID; useEffect(() =gt; { axios.get("http://localhost:8000/getuserid/" argu).then((response) =gt; { setCmpnyCode(response.data[0].CmpnyCode); setUserID(response.data[0].UserID); setUserFullName(response.data[0].UserFullName); setUserDetail(response.data[0].UserDetail); setLoginID(response.data[0].LoginID); setPassword(response.data[0].Password); setUserPin(response.data[0].UserPin); setUserEmailID(response.data[0].UserEmailID); setUserFP(response.data[0].UserFP); //setPhoto(response.data[0].Photo); setIsActive(response.data[0].IsActive.data[0]); setLicCount(response.data[0].LicCount); setDateCreated(response.data[0].DateCreated); setCreatedBy(response.data[0].CreatedBy); setRecordChanged(response.data[0].RecordChanged.data[0]); setLocationID(response.data[0].LocationID); setisValid(response.data[0].isValid); setisDeleted(response.data[0].isDeleted); }); }, [argu]); const editData = () =gt; { axios.put("http://localhost:8000/upusermst/" argu, { CmpnyCode, UserID, UserFullName, UserDetail, LoginID, Password, UserPin, UserEmailID, UserFP, // Photo, IsActive, LicCount, DateCreated, CreatedBy, RecordChanged, LocationID, isValid, isDeleted, }); history.push("/usermst"); }; const uploadPhoto = (event, argu) =gt; { event.preventDefault(); const formData = new FormData(); formData.append("avatar", Photo); fetch("http://localhost:8000/uploadphoto/" argu, { method: "PUT", body: formData, }); }; return ( lt;div className="App"gt; lt;div className="auth-wrapper"gt; lt;div className="auth-inner"gt; lt;form enctype="multipart/form-data"gt; lt;h3gt; Edit User Masterlt;/h3gt; lt;divgt; lt;div className="form-class8"gt; lt;div className="form-group"gt; lt;labelgt;Company Codelt;/labelgt; lt;input type="text" className="form-control" placeholder="CompanyCode" value={CmpnyCode} onChange={(e) =gt; { setCmpnyCode(e.target.value); }} name="CmpnyCode" /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;UserIDlt;/labelgt; lt;input type="text" className="form-control" placeholder="UserID" value={UserID} onChange={(e) =gt; { setUserID(e.target.value); }} name="UserID" /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;UserFullNamelt;/labelgt; lt;input type="text" className="form-control" placeholder="UserFullName" value={UserFullName} onChange={(e) =gt; { setUserFullName(e.target.value); }} name="UserFullName" /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;UserDetaillt;/labelgt; lt;input type="text" className="form-control" placeholder="UserDetail" onChange={(e) =gt; { setUserDetail(e.target.value); }} name="UserDetail" value={UserDetail} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;LoginIDlt;/labelgt; lt;input type="text" className="form-control" placeholder="LoginID" onChange={(e) =gt; { setLoginID(e.target.value); }} name="LoginID" value={LoginID} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;Passwordlt;/labelgt; lt;input type="text" className="form-control" placeholder="Password" onChange={(e) =gt; { setPassword(e.target.value); }} name="Password" value={Password} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;UserPinlt;/labelgt; lt;input type="text" className="form-control" placeholder="UserPin" onChange={(e) =gt; { setUserPin(e.target.value); }} name="UserPin" value={UserPin} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;UserEmailIDlt;/labelgt; lt;input type="email" className="form-control" placeholder="UserEmailID" onChange={(e) =gt; { setUserEmailID(e.target.value); }} name="UserEmailID" value={UserEmailID} /gt; lt;/divgt; lt;/divgt; lt;div className="form-class8"gt; lt;div className="form-group"gt; lt;labelgt;UserFPlt;/labelgt; lt;input type="file" className="form-control" placeholder="UserFP" onChange={(e) =gt; { setUserFP(e.target.value); }} name="UserFP" /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;Photolt;/labelgt; lt;input type="file" className="form-control" placeholder="Photo" onChange={(e) =gt; { setPhoto(e.target.files[0]); }} id="Photo" name="Photo" /gt; lt;button onClick={(event) =gt; uploadPhoto(event)}gt; Upload lt;/buttongt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;IsActivelt;/labelgt; lt;input type="text" className="form-control" placeholder="IsActive" onChange={(e) =gt; { setIsActive(e.target.value); }} name="IsActive" value={IsActive} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;LicCountlt;/labelgt; lt;input type="text" className="form-control" placeholder="LicCount" onChange={(e) =gt; { setLicCount(e.target.value); }} name="LicCount" value={LicCount} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;DateCreatedlt;/labelgt; lt;input type="text" className="form-control" placeholder="DateCreated" onChange={(e) =gt; { setDateCreated(e.target.value); }} name="DateCreated" value={DateCreated} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;CreatedBylt;/labelgt; lt;input type="text" className="form-control" placeholder="CreatedBy" onChange={(e) =gt; { setCreatedBy(e.target.value); }} name="CreatedBy" value={CreatedBy} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;RecordChangedlt;/labelgt; lt;input type="text" className="form-control" placeholder="RecordChanged" onChange={(e) =gt; { setRecordChanged(e.target.value); }} name="RecordChanged" value={RecordChanged} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;LocationIDlt;/labelgt; lt;input type="text" className="form-control" placeholder="LocationID" onChange={(e) =gt; { setLocationID(e.target.value); }} name="LocationID" value={LocationID} /gt; lt;/divgt; lt;/divgt; lt;div className="form-class8"gt; lt;div className="form-group"gt; lt;labelgt;isValidlt;/labelgt; lt;input type="date" className="form-control" placeholder="isValid" onChange={(e) =gt; { setisValid(e.target.value); }} name="isValid" value={isValid} /gt; lt;/divgt; lt;div className="form-group"gt; lt;labelgt;isDeletedlt;/labelgt; lt;input type="date" className="form-control" placeholder="isDeleted" onChange={(e) =gt; { setisDeleted(e.target.value); }} name="isDeleted" value={isDeleted} /gt; lt;/divgt; lt;/divgt; lt;button className="btn btn-primary btn-block" onClick={() =gt; editData()} gt; Edit lt;/buttongt; lt;/divgt; lt;/formgt; lt;/divgt; lt;/divgt; lt;/divgt; ); } export default withRouter(UserMaster_Edit);
Я пытаюсь работать с разделом «Фото» здесь
index.js:
const multer = require("multer"); const fs = require("fs"); const upload = multer({ dest: "uploads/" }); app.put("/uploadphoto/:UserId", upload.single("avatar"), (req, res) =gt; { const userid = req.params.userId; const photo = req.file; const fileType = photo.mimetype.split("/")[1]; let newFileName = photo.filename "." fileType; fs.rename( `./uploads/${photo.filename}`, `./uploads/${newFileName}`, function () { console.log("file renamed and uploaded"); } ); console.log(photo); console.log("fileName ", newFileName); db.query( "UPDATE usermst SET Photo=? WHERE UserID=?", [newFileName, userid], (err, result) =gt; { console.log(err); res.json({ result }); } ); });
Ответ №1:
Я только что понял, в чем здесь проблема. Очень мелкая деталь. В функции загрузки фотографий я передаю два аргумента: событие и аргумент. Аргумент не определен, следовательно, идентификатор пользователя не передается, он тоже не определен. Функция должна выглядеть следующим образом:
const uploadPhoto = (event) =gt; { event.preventDefault(); const formData = new FormData(); formData.append("avatar", Photo); fetch("http://localhost:8000/uploadphoto/" argu, { method: "PUT", body: formData, }); };``` This should pass the correct userID and update the database as well.