Skip to content
Snippets Groups Projects
PostWrite.js 6.53 KiB
Newer Older
import React, { useRef, useState, useEffect, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
Jaeyong Lee's avatar
Jaeyong Lee committed

import { UserContext } from '../Usercontext.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)
		})
      });
Jaeyong Lee's avatar
Jaeyong Lee committed

Hyun Woo Jeong's avatar
Hyun Woo Jeong committed

Jaeyong Lee's avatar
Jaeyong Lee committed
    const [inputs, setInputs] = useState({
        title: "",
        content: "",
        imageUrls: [],
Jaeyong Lee's avatar
Jaeyong Lee committed
    });

    const [previewImg, setPreviewImg] = useState({
        imageUrls: [],
    });
    const imgRef = useRef();

    // 이미지 업로드 input의 onChange
    const saveImgFile = async () => {
        console.log(imgRef.current.files)
        const file = imgRef.current.files[0];
        console.log(file)
        inputs.imageUrls.push(file);
        setInputs({
            ...inputs,
            imageUrls: inputs.imageUrls
        })

        const reader = new FileReader();
        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"}}
        />
        )
    }
    );

Jaeyong Lee's avatar
Jaeyong Lee committed
    const handleSubmit= async (event) => {
        event.preventDefault();
Jaeyong Lee's avatar
Jaeyong Lee committed
        try {
            console.log(inputs)
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
			const response = await axios({
				url: 'http://localhost:8080/post/upload', // 통신할 웹문서
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
				method: 'post', // 통신할 방식
                headers: {'Content-Type': 'multipart/form-data', charset: 'utf-8'},
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
				data: inputs
			});
			if (response.status === 200) {
                MoveTo('/')
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
				return response.data;
			}
			else {
				return null;
			}
            
Jaeyong Lee's avatar
Jaeyong Lee committed
        }
        catch (error){
            console.log('Error during post creation:', error);
        }
    }
Jaeyong Lee's avatar
Jaeyong Lee committed

    const onChange = (e) => {
        const {value, name} = e.target;
        setInputs({
            ...inputs,
            [name]: value
        });
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
    const [inputs, setInputs] = useState({
        title: "",
        content: "",
    });
    const [content, setContent] = useState("");
    const [uploadedImg, setUploadedImg] = useState({
      fileName: "",
      fillPath: ""
    });
    const BASE_URL = "http://localhost:3000";

Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
    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();
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); 
        
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
          .post("http://localhost:8080/post/upload", formData,
            {
                headers: {"Content-Type": "multipart/form-data"}
            })
          .then(res => {
            const { fileName } = res.data;
            console.log(fileName);
            setUploadedImg({ fileName, filePath: `${BASE_URL}/img/${fileName}` });
            alert("The file is successfully uploaded");
          })
          .catch(err => {
            console.error(err);
          });
      };
Jaeyong Lee's avatar
Jaeyong Lee committed

    return(
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
        <section>
            <div style={{float: "left"}}>
                <SearchMap loc={location} setLoc={setLocation}></SearchMap>
            </div>
            <div style={{float: "right"}}>
                <form onSubmit={onSubmit}>
                    <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>    


Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
		<div>
			<aside style={{float: "left"}}>
				<SearchMap loc={location} setLoc={setLocation}></SearchMap>
			</aside>
			<main style={{float: "right"}}>
				<form onSubmit={handleSubmit} enctype="multipart/form-data">
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
					<div>
						<label>제목</label>
						<input
							type="text"
							name='title'
							//value={title}
							onChange={onChange}
							required
						/>
					</div>
					<div>
						<label>Content</label>
						<textarea
						name='content'
						//value={content}
						onChange={onChange}
						/>
					</div>
					<button style={{height:"50px"}}>wow</button>
                    <div>
                        {imglist}
                        <label className="signup-profileImg-label" htmlFor="profileImg">이미지 추가</label>
                        <input
                            name="image"
                            style={{ display: "none"}}
                            className="signup-profileImg-input"
                            type="file"
                            accept="image/*"
                            id="profileImg"
                            onChange={()=>{saveImgFile()}}
                            ref={imgRef}/>
                    </div>
Hyun Woo Jeong's avatar
Hyun Woo Jeong committed
				</form>
			</main>
		</div>
Jaeyong Lee's avatar
Jaeyong Lee committed
    )
Jaeyong Lee's avatar
Jaeyong Lee committed
export default PostWrite;