package com.oraclejava.es.api.model;

import org.springframework.data.annotation.Transient;
import org.springframework.data.elasticsearch.annotations.Document;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

@Document(indexName = "library", type = "_doc", shards = 2)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Movie {
   private String id;
   private String title;
   private int price;
   private String synopsis;

   private byte[] moviePicture;

// @Transient
// private MultipartFile img;
}
package com.oraclejava.es.api.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.oraclejava.es.api.model.Movie;
import com.oraclejava.es.api.repository.MovieRepository;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class MovieRestController {

   @Autowired
   private MovieRepository movieRepository;
   
   @PostMapping(value="/saveMovie", produces= MediaType.APPLICATION_JSON_VALUE,
         consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
   public int saveMovie(@RequestPart Movie movie, @RequestPart MultipartFile img) {
      //movies.stream().map(m -> m.setId(UUID.randomUUID()))
      List<Movie> newMovies = new ArrayList<>();
      //for (Movie m : movies) {
      movie.setId((movie.getId() != null)?movie.getId():UUID.randomUUID().toString());
         if (img != null) {
            try {
               movie.setMoviePicture(img.getBytes());
            } catch (IOException e) {
               throw new RuntimeException(e);
            }
         }
         newMovies.add(movie);
      //}
      movieRepository.saveAll(newMovies);
      return newMovies.size();
   }
   
   @DeleteMapping("/deleteMovie/{id}")
   public String deleteMovie(@PathVariable String id) {
      movieRepository.deleteById(id);
      return id;
   }
   
   @GetMapping({"/findAllMovies/{page}", "/findAllMovies"})
   public Iterable<Movie> findAllMovies(@PathVariable(required = false) Integer page) {
      page = (page == null) ? 1 : page;
      return movieRepository.findAll(PageRequest.of(page-1, 10, Sort.by("title")));
   }
   
   @GetMapping({"/findByTitle/{title}","/findByTitle/{title}/{page}"})
   public Iterable<Movie> findByTitle(@PathVariable String title, @PathVariable(required = false) Integer page) {
      page = (page == null) ? 1 : page;
      return movieRepository.findByTitle(title,PageRequest.of(page-1, 10, Sort.by("title")));
   }
   
   @GetMapping("/detailMovie/{id}")
   public Movie detail(@PathVariable String id) {
      System.out.println(id);
      return movieRepository.findById(id).get();
   }
}









import React, { useRef } from 'react';
import { useNavigate } from 'react-router';
import './main.css';
function AddMovie() {
    const navigate = useNavigate();
    //const id = useRef();
    const title = useRef();
    const price = useRef();
    const synopsis = useRef();
    const img = useRef();
    return (
        <>
            <h2>영화 추가</h2>
            <table>
                <tbody>
                    {/* <tr>
                        <td>영화ID</td>
                        <td><input ref={id} /></td>
                    </tr> */}
                    <tr>
                        <td>영화제목</td>
                        <td><input ref={title} /></td>
                    </tr>
                    <tr>
                        <td>가격</td>
                        <td><input type="number" ref={price} /></td>
                    </tr>
                    <tr>
                        <td>줄거리</td>
                        <td><textarea rows="5"
                                cols="60"
                                ref={synopsis} /></td>
                    </tr>
                    <tr>
                        <td>영화이미지</td>
                        <td>
                            <input type='file' ref={img} />
                        </td>
                    </tr>
                    <tr>
                        <td colSpan='2' align='center'>
                            <button type='button' onClick={() => {
                                const form = new FormData();
                                let jsonBodyData = {
                                    'title': title.current.value,
                                    'price': price.current.value,
                                    'synopsis': synopsis.current.value
                                }
                                form.append('movie',  new Blob([JSON.stringify(jsonBodyData)], {
                                    type: 'application/json'
                                  }));

                                form.append('img', img.current.files[0]);
                                fetch('/saveMovie', {
                                    method: 'POST',
                                    // headers: {
                                    //     'Accept': 'application/json',
                                    //     // 'Content-Type': 'multipart/form-data'
                                    // },
                                    // encType: 'multipart/form-data',
                                    body:form
                                }).then(() => {
                                    navigate('/');
                                })
                            }}>
                                추가
                            </button>
                            <button onClick={() => navigate('/')}>영화목록</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </>
    )

}
export default AddMovie;

+ Recent posts