IoT 빅데이터 응용 교육 과정_하계

[IoT 빅데이터 응용 교육과정]23.07.04 파일 업로드

연지양갱 2023. 7. 4. 14:07
728x90
반응형
SMALL

교재

https://thebook.io/080266/0317/

 

스프링 코딩 공작소: 9.1.1 파일 업로드

더북(TheBook): (주)도서출판 길벗에서 제공하는 IT 도서 열람 서비스입니다.

thebook.io

길벗 : 교재 정답 파일 소스파일


 

 

9.1.1 파일 업로드

정적 리소스인 이미지 파일을 처리하는 방법

multipartFile 사용하기

 

 

웹 애플리케이션에서 파일을 업로드 -> 멀티파트

 

서버 업로드 가능 파일 => 텍스트 파일, 바이너리 파일, 이미지 파일, 문서 등 

 

pom.xml 에 파일 업로드 라이브러리 등록

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.11.0</version>
    </dependency>

"dependencies 사이에 저장"

 

 

 

servlet-context.xml에 시큐리티 필터 등록하기

<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <beans:property name="maxUploadSize" value="100000"/> 
    <beans:property name="defaultEncoding" value="utf-8"/> 
    <beans:property name="uploadTempDir" ref="uploadDirResource"/> 
</beans:bean>

<beans:bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
    <beans:constructor-arg value="c:/upload/"/>
</beans:bean>

 

"<beans> 사이에 코드 적용"

maxUploadSize : 업로드 가능한 파일의 최대 크기

defaultEncoding : 인코딩

uploadTempDir : 임시 저장 공간

 

 

폼태그 코드

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="요청 매개변수 이름">
</form>

 

폼 태그 사이에 있는 값을 불러 올 수 있을 것임ㅁ

method 속성 : POST 요청

enctype : 데이터를 보내는 방식은 multipart/form-data이다

input : type=file 파일 을 업로드 하는 것임 ( type : text, file .... )

 

 

 

 

MultipartFile 인터페이스의 개요

 

매개변수 중에서 업로드된 파일 및 데이터를 표현할 때 사용

org.springframework.web.multipart.MultipartFile ---->import

 

메서드 이름 타입 설명
getName() String 멀티파트 폼에서 매개변수 이름을 반환합니다.
getContentType() String 파일의 콘텐츠 형식을 반환합니다.
getOriginalFilename() String 클라이언트의 파일 시스템에서 실제 파일 이름을 반환합니다.
isEmpty() boolean 업로드한 파일이 있는지 반환합니다.
getSize() long 바이트의 파일 크기를 반환합니다.
getBytes() byte[] 바이트의 배열로 파일 내용을 반환합니다.
getInputStream() InputStream 파일 폼의 내용을 읽어 InputStream을 반환합니다.
transferTo(File dest) void 수신된 파일을 지정한 대상 파일에 전송합니다.

InputStream 

 

 

 

@RequestParam

파라미터 값으로 하나하나 파싱해줘야함

매개변수나 업로드한 파일 데이터를 전달 받음

 

controller

package com.springmvc.chap09;

import java.io.File;
import java.io.IOException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


@Controller
@RequestMapping("/exam01")
public class Example01Controller {

    @GetMapping("/form")
    public String requestForm() {
        return "webpage09_01";
    }
    @PostMapping("/form")
    public String submitForm(@RequestParam("name") String name, 
                             @RequestParam("fileImage") MultipartFile file) {
        String filename = file.getOriginalFilename();
        File f = new File("c:\\upload\\" + name + "_" + filename);

        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "webpage09_submit";
    }
}

서버 키고 localhost:8080 .... / exam01/form 작성 -> webpage09_01 페이지를 보여줌

@RequestParam("name") : name이라는 이름을 가진 input값을 가져와서 String 타입의 name에 저장

@RequestParam("fileImage") : fileImage라는 이름을 가진 input값을 가져와서 MultipartFile 타입의 file에 저장함

**** @RequestParam("name") string name => jsp의 name과 같으면 생략 가능

 

 

그리고 해당 파일을 정제하여 저장

file.getOriginalFilename(); 

c://upload// + name + _ + filename : 경로에 데이터를 저장함

 

 

 

 

jsp 파일

webpage09_01.jsp

<%@ page contentType="text/html; charset=utf-8"%>
<html>
<head>
<title>File Upload</title>
</head>
<body>
	<h3>파일업로드</h3>
	<form action ="form"  method="post" enctype="multipart/form-data">
		<p>이름 : <input type="text"  name="name"/> 		
		<p>파일 : <input type="file" name="fileImage"/> 		
		<p><input type="submit" value="전송하기"/> 
		   <input type="reset"  value="다시쓰기"/>			
	</form>
</body>
<html>

webpage09_submit.jsp

<%@ page contentType="text/html; charset=utf-8"%>

<html>
<head>
<title>File Upload</title>
</head>
<body>
	<h3>파일업로드</h3>
	파일업로드 성공했습니다.
</body>
<html>

 

security 관련 코드 작성했던 내용은 삭제해야함ㅁ

pom.xml

web.xml

...

확인하면 된다

 

 

 

 

MultipartRequest

 

메서드 이름 타입 설명
getFile(String name) MultipartFile 이 요청에 업로드된 파일의 설명과 내용을 반환합니다. 없을 때는 null을 반환합니다.
getFileMap() Map<String, MultipartFile> 이 요청에 포함된 멀티파트 파일의 Map을 반환합니다.
getFileNames() Iterator<String> 이 요청에 포함된 멀티파트의 매개변수 이름이 포함된 String 객체의 Iterator를 반환합니다.
getFiles(String name) List<MultipartFile> 이 요청에 업로드된 파일의 내용과 설명을 반환합니다. 없으면 빈 List를 반환합니다.
getMultiFileMap() MultiValueMap<String,MultipartFile> 이 요청에 포함된 멀티파트의 MultiValueMap을 반환합니다.
getMultipartContentType(String aramOrFileName) String 지정된 요청 부분의 content 타입을 결정합니다.

중요!!

 

servlet-context.xml

내에 아래 코드 입력해주기

c:/upload/ 파일 경로를 입력해줘야함

	<beans:bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    	<beans:property name="maxUploadSize" value="10000000"/>  
    	<beans:property name="defaultEncoding" value="utf-8"/>  
    	<beans:property name="uploadTempDir"   ref="uploadDirResource"/> 
	</beans:bean>

	<beans:bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
        <beans:constructor-arg value="c:/upload/" />           
    </beans:bean>

 

 

 

bookMarket

 

 

 

 

 

 

 

 

 

 

반응형