2022-03-24(목)

Jeongyun Heo·2022년 3월 24일
0

HTTP 요청 파라미터의 값 다루기

① GET 요청 -> ?name=OOO&ageO
URL에 값 포함

② POST 요청 -> message-body에 값 포함

③ POST 요청 -> multipart/form-data

Spring Framework ---call---> handler(String name, int age) {...}

Spring Framework가 데이터를 추출해서 메서드를 호출할 때 파라미터로 넘겨준다

javascript fileupload 검색

https://developer.mozilla.org/ko/docs/Web/API/File/Using_files_from_web_applications

<form id="form1">
  이름: <input type="text" name="name"><br>
  나이: <input type="number" name="age"><br>
  사진: <input type="file" name="photo"><br>
  <button id="btn" type="button">요청</button>
</form>

<script>
document.querySelector("#btn").onclick = function() {
	console.log("ok!");
};
</script>

http://localhost:8080/html/form/exam-21.html

button의 type을 지정하지 않으면 기본이 submit 버튼
버튼을 누르는 순간 버튼이 속해 있는 form의 입력값을 서버에 요청을 보낸다
일반 버튼으로 만들려면 type="button"으로 하기
action에 url이 지정되어 있지 않으면 현재 url로 요청한다

https://developer.mozilla.org/ko/docs/Web/API/File/Using_files_from_web_applications#example_uploading_a_user-selected_file

Controller에 있는 메서드는
클라이언트에서 요청이 들어올 때 스프링부트가 호출
요청을 다루는 일을 한다
Controller에 있는 메서드를 Request Handler 라고 한다

동기식, 비동기식
web/src/main/resources/static/javascript/ex07
나중에 공부하기

<script>
document.querySelector("#btn").onclick = function() {
	// 비동기 요청 작업을 수행할 객체를 준비한다.
	var xhr = new XMLHttpRequest();
	
	// 서버에 연결한다.
	xhr.open(
			"POST", 
			"/html/form/exam21", // 요청 URL
			false // 비동기 여부
	);
	
	// 서버에 POST 방식으로 데이터를 보내는 경우 다음과 같이 MIME 타입을 설정해야 한다.
	xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	
	// 서버에 요청한다.
	// => 동기 방식일 경우 서버에서 응답이 올 때까지 리턴하지 않는다.
	xhr.send("name=aaa&age=22");
	
	// 서버의 응답을 꺼낸다.
	console.log(xhr.responseText);
};
</script>
  @RequestMapping("/html/form/exam21")
  public Object exam21(String name, int age) throws Exception {
    System.out.println(name);
    System.out.println(age);

    Thread.sleep(10000);

    return "ok!";
  }

동기 방식일 경우 서버에서 응답이 올 때까지 리턴하지 않는다.
요청 버튼 누르니까 UI가 block 됨

비동기 요청이 필요한 이유

multipart 데이터를 보내는 방법

var fName = document.querySelector("input[name=name]");
var fAge = document.querySelector("input[name=age]");

console.log(fName.value, fAge.value);
xhr.send(`name=${fName.value}&age=${fAge.value}`);

FormData()
https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

https://developer.mozilla.org/ko/docs/Web/API/File/Using_files_from_web_applications#example_uploading_a_user-selected_file

var fPhoto = document.querySelector("input[type=file]");

document.querySelector("#btn").onclick = function() {
	
	console.log(fPhoto.files);
};

multiple

사진: <input type="file" name="photo" multiple><br>

파일까지 넘어감..

var fd = new FormData(document.querySelector("#form1"));

<form name="form1">
var fd = new FormData(document.forms.namedItem("form1"));

사진 파일명이 같으면 사진 파일이 덮어쓰기 된다..

그래서 저장할 때 오리지날 이름으로 저장하면 안 됨

오리지널 이름으로 저장하지 않고 임의의 랜덤한 이름을 쓴다

System.out.println(UUID.randomUUID().toString());

파일 이름 달라져도 잘 나옴

확장자 붙이기

          String filename = UUID.randomUUID().toString();
          int dotIndex = part.getOriginalFilename().lastIndexOf(".");
          if (dotIndex != -1) {
            filename += part.getOriginalFilename().substring(dotIndex);
          }

데이터베이스에 저장할 파일명

절대 파일이름이 겹치지 않는다

javascript fetch formdata 검색

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_multiple_files

0개의 댓글