[Web_3] Spring 6 πŸ˜—

08627Β·2022λ…„ 9μ›” 21일
1

Spring

λͺ©λ‘ 보기
6/13
post-thumbnail


πŸ“Œ Form Data ν˜•μ‹μœΌλ‘œ μ²¨λΆ€νŒŒμΌ μ „μ†‘ν•˜κ³  λ°›μ•„μ˜€κΈ°

πŸ‘Ύ News : 기사와 μ²¨λΆ€νŒŒμΌμ„ μ„œλ²„μ— μ—…λ‘œλ“œν•˜κΈ°

▫️ newsAjax.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
    <style>
       ... 
    </style>
</head>
<body>
    <div id="container">
        <form enctype="multipart/form-data">
            <table>
                <thead>
                    <tr>
                        <th colspan="2">
                            <h1>λ‰΄μŠ€μ •λ³΄</h1>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <th>
                            <label for="title">제λͺ©</label>
                        </th>
                        <td>
                            <input type="text" id="title" name="title">
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="broadcasting-name">방솑ꡭλͺ…</label>
                        </th>
                        <td>
                            <input type="text" id="broadcasting-name" name="broadcastingName">
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="broadcasting-name">첨뢀이미지</label>
                        </th>
                        <td>
                            <!-- 파일, 이미지 -->
                            <input type="file" name="files" accept="image/jpeg, image/png, image/jpg, image/gif" multiple>
                        </td>
                    </tr>
                    <tr>
                        <th>
                            <label for="content">κΈ°μ‚¬λ‚΄μš©</label>
                        </th>
                        <td>
                            <textarea id="content" name="content"></textarea>
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="2">
                            <button type="button" class="write-button">μž‘μ„±ν•˜κΈ°</button>
                        </th>
                    </tr>
                </tfoot>
            </table>
        </form>
        <div class="preview">

        </div>
    </div>

    <script>
    // 'μž‘μ„±ν•˜κΈ°' λ²„νŠΌ 클릭 μ‹œ Ajax 둜
    // μ„œλ²„μ— 폼 데이터 ν˜•μ‹μœΌλ‘œ 기사와 μ²¨λΆ€νŒŒμΌμ„ ν•¨κ»˜ 전솑(request)함. 
      
        const writeButton = document.querySelector(".write-button");

        writeButton.onclick = () => {
            request();
        }

        function getFormData() {
            const form = document.querySelector("form");
            return new FormData(form);
        }

        function request() {
            $.ajax({
                async: false,
                type: "post",
                url: "/api/news", 
      
      			// form-data 전솑 μ‹œ μ•„λž˜ 3 섀정을 ν•΄μ€˜μ•Ό μ œλŒ€λ‘œ 전솑됨 ❗
                enctype: "multipart/form-data",
                contentType: false, 
                processData: false, 
      
                data: getFormData(),
                dataType: "json",
                success: (response) => {
                    console.log(response);
                    const preview = document.querySelector(".preview");

                    preview.innerHTML = `
                        <h2>제λͺ©: ${response.data.title}</h2>
                        <h2>방속ꡭλͺ…: ${response.data.broadcastingName}</h2>
                        <h2>λ‚΄μš©: ${response.data.content}</h2>
                        <h2>파일 리슀트</h2>
                    `;

                    for(let i = 0; i < response.data.fileNames.length; i++) {
                        preview.innerHTML += `
                            <h3>${response.data.fileNames[i]}</h3>
                        `;
                    }
                },
                error: (error) => {
                    console.log(error);
                }
            })
        }
    </script>
</body>
</html>

<input> νƒœκ·Έμ˜ name 으둜 μ„œλ²„μ—μ„œ 폼 데이터λ₯Ό μ°Έμ‘°ν•  λ•Œ μ‚¬μš©ν•  이름을 지정해쀀닀.
DTO의 ν•„λ“œλͺ…κ³Ό 동일해야 DTO 객체에 μš”μ²­ 데이터λ₯Ό λ‹΄μ•„μ˜¬ 수 μžˆλ‹€.

▫️ AddNewsReqDto.java

@Data
public class AddNewsReqDto {
    private String title;
    private String broadcastingName;
    private List<MultipartFile> files;
    private String content;
}

▫️ NewsController

@Slf4j
@RestController
public class NewsController {
    @PostMapping("/api/news")
    public ResponseEntity<?> addNews(AddNewReqDto addNewReqDto){
		
        log.info("{}", addNewReqDto);
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", addNewReqDto.getTitle());
        map.put("broadcastingName", addNewReqDto.getBroadcastingName());
        map.put("content", addNewReqDto.getContent());

        List<String> fileNameList = new ArrayList<String>();
        addNewReqDto.getFiles().forEach((file) -> {
            fileNameList.add(file.getOriginalFilename());
        });
        map.put("fileNames", fileNameList);

        return ResponseEntity.ok(new CMRespDto<>(1, "λ‰΄μŠ€ 등둝 μ™„λ£Œ", map));
    }
}

@RequestBody μ–΄λ…Έν…Œμ΄μ…˜μ— μ˜ν•΄
map 으둜 응닡 데이터λ₯Ό 보내면 β†’ JSON 객체둜 보내짐.


πŸ“’ μ†Œκ° πŸ˜—

0개의 λŒ“κΈ€