• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

비디오 업로드 폼 질문드려요

20.09.16 19:08 작성 조회수 211

0

강의 잘 보고 있습니다.

비디오 업로드 폼에서 콘솔에 파일 이름과 경로는 나오는데 왜 영화/애니, 비공개/공개 설정하고 submit 버튼 누르면 

'Please first fill all the fields'

팝업창이 왜 뜨는지 궁금합니다.

썸네일 504 에러도 궁금하구요 ㅜㅜ

UploadVideoPage.js 코드 첨부합니다.

import React, { useStateuseEffect } from 'react'
import { TypographyButtonFormInputIcon } from 'antd';
import Dropzone from 'react-dropzone';
import axios from 'axios';
import { useSelector } from "react-redux";

const { Title } = Typography;
const { TextArea } = Input;

const Private = [
    { value: 0, label: '비공개' },
    { value: 1, label: '공개' }
]

const Catogory = [
    { value: 0, label: "영화/애니메이션" },
    { value: 0, label: "자동차" },
    { value: 0, label: "음악" },
    { value: 0, label: "동물" },
    { value: 0, label: "스포츠" },
]

function UploadVideoPage(props) {
    const user = useSelector(state => state.user);

    const [titlesetTitle= useState("");
    const [DescriptionsetDescription= useState("");
    const [privacysetPrivacy= useState(0)
    const [CategoriessetCategories= useState("영화/애니메이션")
    const [FilePathsetFilePath= useState("")
    const [DurationsetDuration= useState("")
    const [ThumbnailsetThumbnail= useState("")


    const handleChangeTitle = (event=> {
        setTitle(event.currentTarget.value)
    }

    const handleChangeDecsription = (event=> {
        console.log(event.currentTarget.value)

        setDescription(event.currentTarget.value)
    }

    const handleChangeOne = (event=> {
        setPrivacy(event.currentTarget.value)
    }

    const handleChangeTwo = (event=> {
        setCategories(event.currentTarget.value)
    }

    const onSubmit = (event=> {

        event.preventDefault();

        if (user.userData && !user.userData.isAuth) {
            return alert('Please Log in First')
        }

        if (title === "" || Description === "" ||
            Categories === "" || FilePath === "" ||
            Duration === "" || Thumbnail === "") {
            return alert('Please first fill all the fields')
        }

        const variables = {
            writer: user.userData._id,
            title: title,
            description: Description,
            privacy: privacy,
            filePath: FilePath,
            category: Categories,
            duration: Duration,
            thumbnail: Thumbnail
        }

        axios.post('/api/video/uploadVideo'variables)
            .then(response => {
                if (response.data.success) {
                    alert('video Uploaded Successfully')
                    props.history.push('/')
                } else {
                    alert('Failed to upload video')
                }
            })

    }

    const onDrop = (files=> {

        let formData = new FormData();
        const config = {
            header: { 'content-type''multipart/form-data' }
        }
        console.log(files)
        formData.append("file"files[0])

        axios.post('/api/video/uploadfiles'formDataconfig)
            .then(response => {
                if (response.data.success) {
                    console.log(response.data);
                    
                    let variable = {
                        filePath: response.data.filePath,
                        fileName: response.data.fileName
                    }
                    setFilePath(response.data.filePath)

                    //gerenate thumbnail with this filepath ! 

                    axios.post('/api/video/thumbnail'variable)
                        .then(response => {
                            if (response.data.success) {
                                setDuration(response.data.fileDuration)
                                setThumbnail(response.data.thumbsFilePath)
                            } else {
                                alert('Failed to make the thumbnails');
                            }
                        })


                } else {
                    alert('failed to save the video in server')
                }
            })

    }

    return (
        <div style={{ maxWidth: '700px', margin: '2rem auto' }}>
            <div style={{ textAlign: 'center', marginBottom: '2rem' }}>
                <Title level={2> Upload Video</Title>
            </div>

            <Form onSubmit={onSubmit}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Dropzone
                        onDrop={onDrop}
                        multiple={false}
                        maxSize={800000000}>
                        {({ getRootPropsgetInputProps }) => (
                            <div style={{ width: '300px', height: '240px', border: '1px solid lightgray', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
                                {...getRootProps()}
                            >
                                <input {...getInputProps()/>
                                <Icon type="plus" style={{ fontSize: '3rem' }/>

                            </div>
                        )}
                    </Dropzone>

                    {Thumbnail !== "" &&
                        <div>
                            <img src={`http://localhost:5000/${Thumbnail}`alt="haha" />
                        </div>
                    }
                </div>

                <br /><br />
                <label>Title</label>
                <Input
                    onChange={handleChangeTitle}
                    value={title}
                />
                <br /><br />
                <label>Description</label>
                <TextArea
                    onChange={handleChangeDecsription}
                    value={Description}
                />
                <br /><br />

                <select onChange={handleChangeOne}>
                    {Private.map((itemindex=> (
                        <option key={indexvalue={item.value}>{item.label}</option>
                    ))}
                </select>
                <br /><br />

                <select onChange={handleChangeTwo}>
                    {Catogory.map((itemindex=> (
                        <option key={indexvalue={item.label}>{item.label}</option>
                    ))}
                </select>
                <br /><br />

                <Button type="primary" size="large" onClick={onSubmit}>
                    Submit
            </Button>

            </Form>
        </div>
    )
}

export default UploadVideoPage

Video.js 코드도 첨부합니다.

const express = require('express');
const router = express.Router();
const multer = require('multer');
var ffmpeg = require('fluent-ffmpeg');

const { Video } = require("../models/Video");
const { Subscriber } = require("../models/Subscriber");
const { auth } = require("../middleware/auth");

var storage = multer.diskStorage({
    destination: (reqfilecb=> {
        cb(null'uploads/')
    },
    filename: (reqfilecb=> {
        cb(null`${Date.now()}_${file.originalname}`)
    },
    fileFilter: (reqfilecb=> {
        const ext = path.extname(file.originalname)
        if (ext !== '.mp4') {
            return cb(res.status(400).end('only jpg, png, mp4 is allowed'), false);
        }
        cb(nulltrue)
    }
})

const upload = multer({ storage: storage }).single("file")




//클라이언트가 올린 비디오를 서버에 전달한다
router.post("/uploadfiles", (reqres=> {

    upload(reqreserr => {
        if (err) {
            return res.json({ success: falseerr })
        }
        return res.json({ success: true, filePath: res.req.file.path, fileName: res.req.file.filename })
    })

});


router.post("/thumbnail", (reqres=> {

    let thumbsFilePath ="";
    let fileDuration ="";

    ffmpeg.ffprobe(req.body.filePathfunction(errmetadata){
        console.dir(metadata);
        console.log(metadata.format.duration);

        fileDuration = metadata.format.duration;
    })


    ffmpeg(req.body.filePath)
        .on('filenames'function (filenames) {
            console.log('Will generate ' + filenames.join(', '))
            thumbsFilePath = "uploads/thumbnails/" + filenames[0];
        })
        .on('end'function () {
            console.log('Screenshots taken');
            return res.json({ success: true, thumbsFilePath: thumbsFilePath, fileDuration: fileDuration})
        })
        .screenshots({
            // Will take screens at 20%, 40%, 60% and 80% of the video
            count: 3,
            folder: 'uploads/thumbnails',
            size:'320x240',
            // %b input basename ( filename w/o extension )
            filename:'thumbnail-%b.png'
        });

});




router.get("/getVideos", (reqres=> {

    Video.find()
        .populate('writer')
        .exec((errvideos=> {
            if(errreturn res.status(400).send(err);
            res.status(200).json({ success: truevideos })
        })

});



router.post("/uploadVideo", (reqres=> {

    const video = new Video(req.body)

    video.save((errvideo=> {
        if(errreturn res.status(400).json({ success: falseerr })
        return res.status(200).json({
            success: true 
        })
    })

});


router.post("/getVideo", (reqres=> {

    Video.findOne({ "_id" : req.body.videoId })
    .populate('writer')
    .exec((errvideo=> {
        if(errreturn res.status(400).send(err);
        res.status(200).json({ success: truevideo })
    })
});


router.post("/getSubscriptionVideos", (reqres=> {


    //Need to find all of the Users that I am subscribing to From Subscriber Collection 
    
    Subscriber.find({ 'userFrom'req.body.userFrom })
    .exec((errsubscribers)=> {
        if(errreturn res.status(400).send(err);

        let subscribedUser = [];

        subscribers.map((subscriberi)=> {
            subscribedUser.push(subscriber.userTo)
        })


        //Need to Fetch all of the Videos that belong to the Users that I found in previous step. 
        Video.find({ writer: { $in: subscribedUser }})
            .populate('writer')
            .exec((errvideos=> {
                if(errreturn res.status(400).send(err);
                res.status(200).json({ success: truevideos })
            })
    })
});

module.exports = router;

뭐가 문제일까요? 도와주세요 ㅜㅜ

답변 1

답변을 작성해보세요.

0

안녕하세요  

우선 console.log하셔서 

어떠한 값이 안들어왔는지 살펴보시겠나요 ? 

예를 들어서 

console.log('title',title) 이런식으로 해서  값이 안들어간것을 먼저 찾아주시면 됩니다 ~ !