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