app.use(e.json());
app.use(e.urlencoded({ extended: false }));
const multer = require("multer");
const path=require('path')
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "20230530_2/imgs"); // Set the destination folder where the uploaded files will be stored
},
filename: (req, file, cb) => {
const ext = path.extname(file.originalname);
const filename =
path.basename(file.originalname, ext) + "_" + Date.now() + ext;
cb(null, filename); // Use the original filename for the stored file
},
limits: { fileSize: 5 * 1024 * 1024 }, //5MB
});
const upload = multer({ storage });
module.exports = upload;
module.exports = upload;로 내보내자
exports.signUp = async (req, res, next) => {
try {
const { filename } = req.file;
const { user_id, user_pw, username } = req.body;
const data = await User.findOne({ where: { user_id } });
if (data == null) {
const hash = bcrypt.hashSync(user_pw, 10);
await User.create({
user_id,
user_pw: hash,
username,
img: filename,
});
res.send("성공");
console.log("req.file");
} else {
res.send("중복됨");
}
} catch (error) {
console.log(error);
}
};
app.use("/img", e.static(path.join(__dirname, "imgs")));
const upload = require("../uploadImg/uploadImg");
const router = require("express").Router();
router.post("/", upload.single("profile"), signUp);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<label for="">name</label>
<input type="text" id="username" />
<label for="">id</label>
<input type="text" id="user_id" />
<label for="">password</label>
<input type="password" id="user_pw" />
<label for="">profile image</label>
<input type="file" id="img" />
<button id="signUpBtn">signUp</button>
</body>
<script>
signUpBtn.onclick = () => {
const form = new FormData();
form.append("user_id", user_id.value);
form.append("user_pw", user_pw.value);
form.append("username", username.value);
form.append("profile", img.files[0]);
console.log(user_id.value);
axios
.post("http://127.0.0.1:8080/signUp", form, {
"Content-Type": "multipart/form-data",
})
.then((e) => {
window.location.href =
"http://127.0.0.1:5500/20230530_2/login.html";
console.log(e, "성공");
})
.catch((err) => {
console.log(err);
});
};
</script>
</html>
const form = new FormData();
form.append("user_id", user_id.value);
form.append("user_pw", user_pw.value);
form.append("username", username.value);
form.append("profile", img.files[0]);
form이라는 새로운 js객체를 선언해서 append로 값을 할당한다.
첫 번째 매개변수는 서버에서 받을 이름(즉,input의 name이다.)을, 두 번째 매개변수로는 전달해줄 값을 입력한다.
img는 files[0]이 그 파일의 정보이다.
axios.post("http://127.0.0.1:8080/signUp", form, {
"Content-Type": "multipart/form-data",
})
axios로 데이터를 보낸다."Content-Type": "multipart/form-data",로 헤더를 꼭 설정해주자
then((e) => {
window.location.href =
"http://127.0.0.1:5500/20230530_2/login.html";
console.log(e, "성공");
})
axios는 절대로 서버단에서 res.redirect와 같은 http요청을 받을 수 없다!
그러므로 클라이언트단에서 이동할 곳을 처리하자
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
ㅎㅇ
<h1 id="name"></h1>
<h1 id="user_id"></h1>
<img src="" alt="profile" id="user_img" />
<a href="http://127.0.0.1:8080/signUp/changeUserProfile">프로필 변경하기</a>
</body>
<script>
window.onload = () => {
axios
.get("http://127.0.0.1:8080/signUp/getAllUserInfo", {
withCredentials: true,
})
.then((e) => {
const { data } = e;
name.innerText = data.username;
user_id.innerText = data.user_id;
user_img.src=`http://127.0.0.1:8080/img/${data.img}`
console.log(e);
})
.catch((err) => {
console.log(e);
});
};
</script>
</html>
위와 같이 파일의 이름만을 Mysql에 저장했으니 백틱으로 이미지의 이름만을 변수로 넣어줘서 화면에 표시해주면 된다.
정말 좋은 글 감사합니다!