I want to store and send images to a database using Spring

I'm working on a web application, and I'm trying to send a POST request to a specific endpoint (/board/writepro). However, I'm encountering the following error message: I'm using Spring, and I'm getting an error message that says:

Content-Type 'application/x-www-form-urlencoded;charset=UTF-8' is not supported

when making a POST request. How can I resolve this issue? Here's my controller class: I am working with a React user on a project

package org.polyproject.fishinghubpro.controller;


import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.polyproject.fishinghubpro.dto.BoardDto;
import org.polyproject.fishinghubpro.entity.Board;
import org.polyproject.fishinghubpro.service.BoardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.security.Principal;
import java.util.List;

@RestController
@CrossOrigin("*")
@Transactional
@Slf4j
public class BoardController {


    @Autowired
    private BoardService boardService;

    @GetMapping("/board/write")//localhost:8090/board/write
    public String boardWriteForm(){

        return "boardwrite";
    }

    //원본
    @PostMapping("board/writepro")
    public ResponseEntity<BoardDto> boardWritePro(@RequestBody Board board, MultipartFile file, Principal principal) throws Exception {
        String userId = principal.getName();

        // boardService.write 메서드로 게시글을 작성하고 게시글 정보를 받아옴
        BoardDto createdBoard = boardService.write(board, file, userId);

        // ResponseEntity로 커스텀 응답을 생성하고, 상태 코드와 함께 반환
        return new ResponseEntity<>(createdBoard, HttpStatus.CREATED); // 수정: response 대신 createdBoard 반환
    }





@GetMapping("/board/list")
public ResponseEntity<List<Board>> boardList(@PageableDefault(page = 0, size = 10, sort = "id", direction = Sort.Direction.DESC) Pageable pageable) {
    Page<Board> list = boardService.boardList(pageable);

    // 게시글 목록을 리스트로 변환
    List<Board> boardList = list.getContent();

    // ResponseEntity를 사용하여 JSON 형식으로 데이터 반환
    return new ResponseEntity<>(boardList, HttpStatus.OK);
}

    @GetMapping("/board/view")//localhost:8080/board/view?id=1
    public String boardView(Model model, Integer id){


        model.addAttribute("board",boardService.boardView(id));
        return "boardview";
    }
    @DeleteMapping("/board/{id}")
    public ResponseEntity<String> deleteBoard(@PathVariable("id") Integer id) {
        try {
            // 게시글 삭제를 시도합니다.
            boardService.boardDelete(id);

            // 게시글이 성공적으로 삭제되었을 때의 응답입니다.
            return ResponseEntity.noContent().build();
        } catch (Exception e) {
            // 게시글 삭제 중 오류가 발생했을 때의 응답입니다.
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("게시글 삭제 중 오류가 발생했습니다.");
        }
    }


    @GetMapping("/board/modify/{id}")
    public String boardModify(@PathVariable("id")Integer id,Model model){

        model.addAttribute("board",boardService.boardView(id));
        return "boardmodify";
    }
    @PostMapping("/board/update/")
    public String boardUpdate(@RequestBody BoardDto board, Principal principal)throws Exception {
        log.info("지나갑니다!~!==={}",board.getId());
        String userId = principal.getName();    //게시글을 쓴 애의 아이디.
        Board boardTemp = boardService.boardView(board.getId());   //기존에 저장된 게시글 가져오기

        //기존에 저장된 게시글에 새로 들어온 데이터로 수정 해주는 구문.
        boardTemp.setTitle(board.getTitle());   //dirtyChecking으로 변경감지로 수정. 따로 저장 구문 필요 없음.
        boardTemp.setContent(board.getContent());
//        boardService.write(boardTemp, file, userId); // 수정된 내용을 저장
        return "수정되었습니다.";
    }

}

package org.polyproject.fishinghubpro.dto;

import lombok.Builder;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.polyproject.fishinghubpro.entity.BaseEntity;

import java.util.Date;

@Data
@Builder
public class BoardDto {

    @Setter@Getter
    private int id;
    private String title;
    private String content;
    private String filename;
    private String filepath;
    private Date createdAt;
    private String memberNick; // 회원 닉네임

    // 생성자, getter, setter 생략
}
package org.polyproject.fishinghubpro.entity;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Data;
import lombok.ToString;
import org.hibernate.annotations.CreationTimestamp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Data
public class Board{

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Integer id;

    private String title;

    @Column(columnDefinition = "TEXT", nullable = false) // content를 TEXT 타입으로 설정하고 NOT NULL 제약 조건 추가
    private  String content;

    @Column(length = 15000 )
    private String filename;

    @Column(length = 30000 )
    private String filepath;

    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "created_at", nullable = false, updatable = false)
    private Date createdAt;

    @ManyToOne
    @ToString.Exclude
    @JoinColumn(name="user_no")
    private Member member;
}

package org.polyproject.fishinghubpro.repository;

import jakarta.transaction.Transactional;
import org.polyproject.fishinghubpro.entity.Board;
import org.polyproject.fishinghubpro.entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
@Transactional
public interface BoardRepository  extends JpaRepository <Board, Integer> {
}

    package org.polyproject.fishinghubpro.service;

    import jakarta.transaction.Transactional;
    import org.polyproject.fishinghubpro.dto.BoardDto;
    import org.polyproject.fishinghubpro.entity.Board;
    import org.polyproject.fishinghubpro.entity.Member;
    import org.polyproject.fishinghubpro.repository.BoardRepository;
    import org.polyproject.fishinghubpro.repository.member.MemberRepository;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;

    import java.util.Date;
    import java.io.File;
    import java.util.List;
    import java.util.UUID;



    @Service
    @Transactional
    public class BoardService {



            @Autowired
            private BoardRepository boardRepository;

            @Autowired
            private MemberRepository memberRepository;

  

            //게시글 리스트 처리
            public Page<Board>boardList(Pageable pageable){

                return boardRepository.findAll(pageable);


            }
            //특정 게시글 불러오기
        public Board boardView(Integer id) {

            return boardRepository.findById(id).get();

        }
        //특정게시글 삭제
        public void boardDelete(Integer id){

                boardRepository.deleteById(id);
        }

        // 게시글 작성 메서드
        public BoardDto write(Board board, MultipartFile file, String userId) throws Exception {
            Member member = memberRepository.findByUserId(userId).orElse(null);

            if (board.getContent() != null && !board.getContent().isEmpty()) {
    //            // 생성 날짜 설정
    //            board.setCreatedAt(new Date());
                // 파일 저장 경로 설정
                String projectPath = System.getProperty("user.dir") + "/src/main/resources/static/files";
                // UUID를 사용하여 파일명 중복 방지
                UUID uuid = UUID.randomUUID();

                // 파일이 업로드되었을 때만 파일 처리
                if (file != null && !file.isEmpty()) {
                    String fileName = uuid + "_" + file.getOriginalFilename();
                    File saveFile = new File(projectPath, fileName);
                    file.transferTo(saveFile);
                    board.setFilename(fileName);
                    board.setFilepath("/files/" + fileName); // 파일 경로 동적 설정
                }
                board.setMember(member);

                Board savedBoard = boardRepository.save(board); // 데이터베이스에 저장

                // 게시글과 회원 닉네임을 포함한 DTO 객체 생성
                BoardDto boardDto = BoardDto.builder()
                                .title(savedBoard.getTitle())
                                        .content(savedBoard.getContent())
                                                .filepath(savedBoard.getFilepath())
                                                        .filename(savedBoard.getFilename())
                                                                .build();
                boardDto.setMemberNick(member.getUserNick());

                return boardDto;
            } else {
                // 콘텐츠가 null 또는 비어 있을 경우 예외 처리
                throw new Exception("게시물 내용을 입력해주세요.");
            }
        }
        }


Thank you for helping me fix this.



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations