Skip to content
Snippets Groups Projects
PostWrite.js 5.33 KiB
Newer Older
import React, { useRef, useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../Context.js';

import SearchMap from '../components/SearchMapByKeyword.js'
import axios from 'axios';
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
axios.defaults.withCredentials = true;

Jaeyong Lee's avatar
Jaeyong Lee committed
function PostWrite(){

Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
    const [location, setLocation] = useState({
        keyword: "",
        center: { lat: null, lng: null }
    });
    const navigate = useNavigate();
	function MoveTo(link){
		navigate(link)
	}	
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
    const userContext = useContext(UserContext);
    useEffect(() => {
        userContext.CheckSession()
        .then((response) => {
            if (!response.data) {
                alert("세션이 만료되었습니다. 다시 로그인 바랍니다.")
                MoveTo('/login')
             }
		})
		.catch((response)=>{
			console.log("error!:LogOut")
			console.log(response)
		})
      });
      const [previewImg, setPreviewImg] = useState({
        imageUrls: [],
Jaeyong Lee's avatar
Jaeyong Lee committed
    });

    const [content, setContent] = useState("");
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
    const [inputs, setInputs] = useState({
        title: "",
        content: "",
    });
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
    const onTextChange = (e) => {
        const {value, name} = e.target;
        setInputs({
            ...inputs,
            [name]: value
        });
    }  
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
    const onImgChange = e => {
        let temp = []
        for (let i=0; i< e.target.files.length; i++) {
            temp.push(e.target.files[i])
        }
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
        setContent(e.target.files);
        Array.from(e.target.files).forEach((file) => {
            const reader = new FileReader();
            console.log(file)
            reader.readAsDataURL(file);
            reader.onloadend = () => {
                previewImg.imageUrls.push(reader.result);
                setPreviewImg({
                    imageUrls: previewImg.imageUrls
                });
            };
        });
      };
      let imglist = [];
      imglist = previewImg.imageUrls.map((image)=>{
          return(
          <img
          src={image ? image :null}
          alt="이미지"
          style={{ width: "100px", height: "100px"}}
          />
          )
      }
      );
    const onSubmit = e => {
        e.preventDefault();

        if (!location.keyword) {
            alert("위치를 알려주세요.");
            return
        }

        if (!inputs.title) {
            alert("제목을 입력해주세요.");
            return
        }

        if (!inputs.content) {
            alert("내용을 입력해주세요.");
            return
        }

        const formData = new FormData();
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
        Array.from(content).forEach((el) => {
            formData.append("img", el);
          });
        formData.append("title", inputs.title); 
        formData.append("content", inputs.content); 
        formData.append("keyword", location.keyword); 
        formData.append("latitude", location.center.lat); 
        formData.append("longitude", location.center.lng); 
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
          .post("http://localhost:8080/post/upload", formData,
            {
                headers: {"Content-Type": "multipart/form-data"}
            })
          .then(res => {
            alert("The file is successfully uploaded");
          })
          .catch(err => {
            console.error(err);
          });
      };
Jaeyong Lee's avatar
Jaeyong Lee committed

    //   <input readOnly={true} type="text" placeholder="장소 키워드" value={location.keyword} />
    //   <input readOnly={true} type="text" placeholder="위도" value={location.center.lat} />
    //   <input readOnly={true} type="text" placeholder="경도" value={location.center.lng} />

Jaeyong Lee's avatar
Jaeyong Lee committed
    return(
        <section style={{display: "flex"}}>
        <div>
            <SearchMap loc={location} setLoc={setLocation}></SearchMap>  
        </div>
        <div>
            <form onSubmit={onSubmit}>
                <div style={{display: "flex"}}>
                    <input readOnly={true} type="text" placeholder="장소 키워드" value={location.keyword} />
                    <button type="button" onClick={()=>{
                        setLocation({
                            keyword: "",
                            center: { lat: null, lng: null }
                        })}}>선택 해제</button>
                </div>
                <div style={{display: "grid"}}>
                    <label>제목</label>
                    <input
                        type="text"
                        name='title'
                        onChange={onTextChange}
                        />
                </div>
                <div style={{display: "grid"}}>
                    <label>Content</label>
                    <input
                        type="text"
                        name='content'
                        onChange={onTextChange}
                        />
                </div>
                <div style={{display: "grid"}}>
                    <div style={{display: "flex"}}>
                    <label htmlFor="profileImg">이미지 업로드</label>
                    <input style={{ display: "none"}} id="profileImg" type="file" onChange={onImgChange} multiple/>   
                </div>
                <button type="submit">포스팅!</button>

            </form>
        </div> 
     
        </section>    
    </> 
Jaeyong Lee's avatar
Jaeyong Lee committed
export default PostWrite;