반응형

작성일자 : 2021.02.20

환경 : 자바8, Spring Boot 2, Chrome

1. 파일 업로드

 

HTML Code

...
  <form method="post" action="/uploadFile" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit">
  </form>
...

 

* submit 대신 Javascript 를 활용할 경우

 

...
	<form method="post" action="/uploadFile" enctype="multipart/form-data">
		<input type="file" name="file">
	</form>
	<button onclick="sendFile()">button</button>
...

<script>
    const sendFile = () => {
        const formElement = document.querySelector("form");
        const request = new XMLHttpRequest();
        request.open("POST", "/uploadFile");
        request.send(new FormData(formElement));
    }
</script>

 

 

Java code

@PostMapping("/uploadFile")
public void uploadFile(@RequestParam("file") MultipartFile file){
    // 파일 기본 정보
    System.out.println("file name : " + file.getOriginalFilename());
    System.out.println("file size : " + file.getSize());

    try(
    	// 프로젝트 폴더에 temp.jpg 이름으로 파일 생성
        FileOutputStream fos = new FileOutputStream("./temp.jpg"); 
        InputStream is = file.getInputStream()
    ){
        int readCount;
        byte[] buffer = new byte[1024];
        
        // 데이터 쓰기
        while((readCount = is.read(buffer)) != -1){
            fos.write(buffer, 0, readCount);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

 

 

2. 파일 다운로드

Java code

@GetMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) {

	// 프로젝트 폴더의 temp.jpg 파일 로드
	String fileName = "temp.jpg";
	File file = new File("./" + fileName);

	// 클라이언트에서 아래의 이름으로 파일이 받아진다.
	String newFileName = "newTemp.jpg";

    try (
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream out = response.getOutputStream()
    ){
    	// 응답이 파일 타입이라는 것을 명시
        response.addHeader("Content-Disposition", "attachment;filename=\""+newFileName+"\"");
        // 응답 크기 명시
        response.setContentLength((int)file.length());

        int read = 0;
        
        // 실제 데이터 전송
        // OutputStream 의 Deafult 버퍼 사이즈는 8192 Byte
        // 이 루프를 8000 번 정도 돌때마다 약 8KB 정도의 데이터가 전송 
        while((read = bis.read()) != -1) {
            out.write(read);
        }
        
    } catch(IOException e) {
        e.printStackTrace();
    }
}

 

---

 

* HTTP MultiPart 로 파일 전송시 formData 에서 확인이 불가능, 단 파일을 null 로 전달하면 확인 가능 (크롬 기준)

 

* form 에서 지정하는 enctype 속성은 아래 세가지의 값으로 지정될 수 있다.

 

1. application/x-www-form-urlencoded

디폴트 값. 폼데이터는 서버로 전송되기 전에 URL-Encode 됨

 

2. multipart/form-data

파일이나 이미지를 서버로 전송할 경우

 

3. text/plain

인코딩을 하지 않은 문자 상태로 전송

 

반응형

'Java > 예제코드' 카테고리의 다른 글

[Spring] JSP 설정  (0) 2021.03.06
[java] 소수점 표현 예제  (0) 2021.02.27
반응형

작성일자 : 2021.02.12

시나리오 : MyBatis 를 사용하여 DB 데이터를 조회할 때 1:M 관계를 가지는 데이터를 List 형태로 조회

환경 : Spring Boot, mybatis-spring-boot-starter 1.3.2

 

 

1. 조회 데이터 정의

 

Parent(1) : Child(M) 구조의 테이블 정의

 

1개의 Parent 데이터와, Parent 와 식별관계를 가지는 2개의 Child 데이터를 저장. Child 는 Parent 의 id 를 FK 로 가짐

 

 

2. 설정

 

* resultMap 을 활용

In Mapper.xml

<resultMap id="parentResultType" type="com.example.demo.Parent">
    <id column="PK 칼럼명" property="멤버 변수명"/>
    <result column="칼럼명" property="멤버 변수명"/>
    <collection property="childList" resultMap="childList"/>
</resultMap>

<resultMap id="childList" type="com.example.demo.Child>
    <id column="PK 칼럼명" property="멤버 변수명"/>
    <result column="칼럼명" property="멤버 변수명"/>
    <result column="칼럼명" property="멤버 변수명"/>
</resultMap>

<select id="selectId" resultMap="parentResultType">
   ...
</select>

 

Mapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.demo.TestMapper">
  
  <resultMap id="parentResultType" type="com.example.demo.Parent">
    <id column="parentId" property="id"/>
    <result column="parentValue" property="value"/>
    <collection property="childList" resultMap="childList"/>
  </resultMap>
  
  <resultMap id="childList" type="com.example.demo.Child">
    <id column="childId" property="id"/>
    <result column="parentId" property="parentId"/>
    <result column="childValue" property="value"/>
  </resultMap>

  <select id="selectParentList" resultMap="parentResultType">
    SELECT
      t1.id AS parentId
      , t1.value AS parentValue
      , t2.id AS childId
      , t2.value AS childValue
    FROM
      parent t1
    LEFT JOIN child t2
    ON t1.id = t2.parentId
  </select>
  
</mapper>

 

Parent.java

public class Parent {
    String id;
    String value;
    List<Child> childList = new ArrayList<>();
}

 

Child.java

public class Child {
    Integer id;
    Integer parentId;
    String value;
}

 

 

3. 확인

 

Mapper 에서 정의한 selectParentList 쿼리를 사용하여 1. 의 환경의 DB 에서 조회할 경우,

 

- 실제 쿼리 조회 내용

 

- 조회한 데이터 내용

 

중복이 제거되고 childList 형태의 멤버 변수가 조회됌 

반응형

'Java' 카테고리의 다른 글

[Spring] Profile 기준 Property 구분 적용  (0) 2023.06.28
[SpringBoot] Gradle 변수 Property 활용  (0) 2022.05.30
[Spring] Web Cache 적용  (0) 2020.12.19
[SpringBoot] H2 연동  (0) 2020.07.21
[Spring] App 구동 후 자동 작업 실행  (0) 2020.02.23
반응형

ECMAScript (ECMA-262)

ECMA 인터내셔널이 제정한 ECMA-262 기술 규격에 의해 정의된 범용 스크립트 언어

ECMAScript 6 는 ECMA-262 표준의 제 6판을 의미(ES6, ES2015, ECMAScript2015 랑 동일한 의미)

 

 

 

JavaScript

ECMAScript 명세 혹은 사양을 준수하는 범용 스크립팅 언어

 

 

reference

wormwlrm.github.io/2018/10/03/What-is-the-difference-between-javascript-and-ecmascript.html

반응형

'용어 정리' 카테고리의 다른 글

상수 / 리터럴  (0) 2021.03.09
함수 표현식 / 함수 선언식  (0) 2021.03.05
코딩 스타일  (0) 2019.09.07
J2SE/J2ME/J2EE  (0) 2018.04.22
CPU/Core/Processor  (0) 2018.04.07

+ Recent posts