Skip to content
Snippets Groups Projects
Commit bb9aaafb authored by Hyun Woo Jeong's avatar Hyun Woo Jeong
Browse files

reworked image upload

parent b11b89a6
No related branches found
No related tags found
No related merge requests found
...@@ -10,7 +10,7 @@ export const router = express.Router(); ...@@ -10,7 +10,7 @@ export const router = express.Router();
const upload = multer({ const upload = multer({
storage: multer.diskStorage({ // 저장한공간 정보 : 하드디스크에 저장 storage: multer.diskStorage({ // 저장한공간 정보 : 하드디스크에 저장
destination(req, file, done) { // 저장 위치 destination(req, file, done) { // 저장 위치
done(null, 'uploads/'); // uploads라는 폴더 안에 저장 done(null, 'public/uploads/'); // uploads라는 폴더 안에 저장
}, },
filename(req, file, done) { // 파일명을 어떤 이름으로 올릴지 filename(req, file, done) { // 파일명을 어떤 이름으로 올릴지
const ext = path.extname(file.originalname); // 파일의 확장자 const ext = path.extname(file.originalname); // 파일의 확장자
...@@ -20,31 +20,23 @@ const upload = multer({ ...@@ -20,31 +20,23 @@ const upload = multer({
limits: { fileSize: 5 * 1024 * 1024 } // 5메가로 용량 제한 limits: { fileSize: 5 * 1024 * 1024 } // 5메가로 용량 제한
}); });
router.post("/upload", upload.single("img"), function(req, res, next) { router.post("/upload", upload.array("img"), async function(req, res, next) {
console.log("/upload")
console.log(req.file)
res.send({
fileName: req.file.filename
});
});
router.post("/upload_temp", async (req, res) => {
console.log("포스팅 '해줘'");
if(!req.session.sessionid){ if(!req.session.sessionid){
// 세션이 없엉 // 세션이 없엉
} }
console.log(req.file); console.log("포스팅 '해줘'");
console.log(req.body)
const inputTitle = req.body.title const inputTitle = req.body.title
const inputContent = req.body.content const inputContent = req.body.content
const inputImage = req.body.imageUrls const inputImage = req.files.map(el => el.path);
const useremail = req.session.sessionid.email const useremail = req.session.sessionid.email
const author = await userService.findUserByEmail(useremail); const author = await userService.findUserByEmail(useremail);
await articleService.createArticle({ await articleService.createArticle({
title: inputTitle, title: inputTitle,
content: inputContent, content: inputContent,
imageUrls: [], imageUrls: inputImage,
author: author, author: author,
comments: [], comments: [],
likes: [] likes: []
...@@ -52,6 +44,7 @@ router.post("/upload_temp", async (req, res) => { ...@@ -52,6 +44,7 @@ router.post("/upload_temp", async (req, res) => {
console.log('saved.') console.log('saved.')
res.send(); res.send();
res.send();
}); });
router.get("/loadarticle", async (req, res) => { router.get("/loadarticle", async (req, res) => {
...@@ -62,7 +55,16 @@ router.get("/loadarticle", async (req, res) => { ...@@ -62,7 +55,16 @@ router.get("/loadarticle", async (req, res) => {
console.log("세션 X") console.log("세션 X")
} }
const articles = await articleService.findAllArticle(); const articles = await articleService.findAllArticle();
console.log(articles)
console.log(JSON.stringify(articles))
res.send(JSON.stringify(articles) ); res.send(JSON.stringify(articles) );
}); });
/*
router.get('/preview', async (req, res, next)=>{
const imgUrl = "http://localhost:3000/images/"
result = imgUrl+"저장된 이미지명" //imgUrl+"kitty.png"
res.send(result);
}
출처: https://avengersrhydon1121.tistory.com/234 [익명의 개발노트:티스토리]
*/
export default router; export default router;
...@@ -2,14 +2,25 @@ import React, {useEffect, useState} from "react"; ...@@ -2,14 +2,25 @@ import React, {useEffect, useState} from "react";
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
function Article(prop) {
console.log(prop)
let listItem = []
listItem = prop.images.map((el)=>{
return(
<img
src={`http://localhost:8080/${el}`}
alt={`http://localhost:8080/${el}`}
style={{ width: "100px", height: "100px"}}/>
)});
function Article(prop) {
return ( return (
<div> <div>
<h1>{prop.title}</h1> <h1>{prop.title}</h1>
<h2>{prop.author}</h2> <h2>{prop.author}</h2>
<p>{prop.content}</p> <p>{prop.content}</p>
<p>{listItem}</p>
{/* 게시글의 내용을 렌더링합니다. */} {/* 게시글의 내용을 렌더링합니다. */}
</div> </div>
); );
......
...@@ -28,6 +28,7 @@ function Main() { ...@@ -28,6 +28,7 @@ function Main() {
title={article.title} title={article.title}
author = {article.author.nickname} author = {article.author.nickname}
content={article.content} content={article.content}
images={article.imageUrls}
></Article> ></Article>
) )
......
...@@ -9,14 +9,15 @@ axios.defaults.withCredentials = true; ...@@ -9,14 +9,15 @@ axios.defaults.withCredentials = true;
function PostWrite(){ function PostWrite(){
const [location, setLocation] = useState({
keyword: "",
/* center: { lat: null, lng: null }
const userContext = useContext(UserContext); });
const navigate = useNavigate(); const navigate = useNavigate();
function MoveTo(link){ function MoveTo(link){
navigate(link) navigate(link)
} }
const userContext = useContext(UserContext);
useEffect(() => { useEffect(() => {
userContext.CheckSession() userContext.CheckSession()
.then((response) => { .then((response) => {
...@@ -30,12 +31,13 @@ function PostWrite(){ ...@@ -30,12 +31,13 @@ function PostWrite(){
console.log(response) console.log(response)
}) })
}); });
/*
const [location, setLocation] = useState({
keyword: "",
center: { lat: null, lng: null }
});
const [inputs, setInputs] = useState({ const [inputs, setInputs] = useState({
title: "", title: "",
...@@ -115,7 +117,10 @@ function PostWrite(){ ...@@ -115,7 +117,10 @@ function PostWrite(){
}); });
} }
*/ */
const [inputs, setInputs] = useState({
title: "",
content: "",
});
const [content, setContent] = useState(""); const [content, setContent] = useState("");
const [uploadedImg, setUploadedImg] = useState({ const [uploadedImg, setUploadedImg] = useState({
fileName: "", fileName: "",
...@@ -123,16 +128,37 @@ function PostWrite(){ ...@@ -123,16 +128,37 @@ function PostWrite(){
}); });
const BASE_URL = "http://localhost:3000"; const BASE_URL = "http://localhost:3000";
const onChange = e => { const onTextChange = (e) => {
setContent(e.target.files[0]); const {value, name} = e.target;
setInputs({
...inputs,
[name]: value
});
}
const onImgChange = e => {
let temp = []
for (let i=0; i< e.target.files.length; i++) {
temp.push(e.target.files[i])
}
setContent(e.target.files);
}; };
const onSubmit = e => { const onSubmit = e => {
e.preventDefault(); e.preventDefault();
const formData = new FormData(); const formData = new FormData();
formData.append("img", content); Array.from(content).forEach((el) => {
formData.append("img", el);
});
formData.append("title", inputs.title);
formData.append("content", inputs.content);
axios axios
.post("http://localhost:8080/post/upload", formData) .post("http://localhost:8080/post/upload", formData,
{
headers: {"Content-Type": "multipart/form-data"}
})
.then(res => { .then(res => {
const { fileName } = res.data; const { fileName } = res.data;
console.log(fileName); console.log(fileName);
...@@ -147,18 +173,36 @@ function PostWrite(){ ...@@ -147,18 +173,36 @@ function PostWrite(){
return( return(
<> <>
<section>
<div style={{float: "left"}}>
<SearchMap loc={location} setLoc={setLocation}></SearchMap>
</div>
<div style={{float: "right"}}>
<form onSubmit={onSubmit}> <form onSubmit={onSubmit}>
{uploadedImg ? ( <div>
<> <label>제목</label>
<img src={uploadedImg.filePath} alt="" /> <input
<h3>{uploadedImg.fileName}</h3> type="text"
</> name='title'
) : ( onChange={onTextChange}
"" required/>
)} </div>
<input type="file" onChange={onChange} /> <div>
<label>Content</label>
<input
type="text"
name='content'
onChange={onTextChange}
required/>
</div>
<input type="file" onChange={onImgChange} multiple/>
<button type="submit">Upload</button> <button type="submit">Upload</button>
</form> </form>
</div>
</section>
</> </>
) )
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment