로메오의 블로그

[Spring Boot] 파일 업로드 처리 - ajax file upload 본문

Backend/Spring

[Spring Boot] 파일 업로드 처리 - ajax file upload

romeoh 2019. 12. 11. 23:57
반응형

Spring Boot / Oracle / Mybatis 차례

 

PersonController

package com.gaeyou.firstproject.contoller;

import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.gaeyou.firstproject.model.PersonModel;
import com.gaeyou.firstproject.model.UploadModel;
import com.gaeyou.firstproject.service.PersonService;

@CrossOrigin
@RestController
@RequestMapping("/persons")
public class PersonController {
	
	@Autowired
	PersonService personService;
	
	@RequestMapping("/all")
	public PersonModel getAll() {		
		return personService.getPerson();
	}
	
	/**
	 * 싱글파일 업로드
	 */
	@PostMapping("/upload/single")
	public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile uploadfile) {		

        if (uploadfile.isEmpty()) {
            return new ResponseEntity("파일을 선택하세요.", HttpStatus.OK);
        }

        try {
        	personService.saveUploadFiles(Arrays.asList(uploadfile));

        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity("업로드 성공 - " + uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK);
	}
	
	/**
	 * 멀티파일 업로드
	 */
	@PostMapping("/upload/multi")
    public ResponseEntity<?> uploadFileMulti(
            @RequestParam("extraField") String extraField,
            @RequestParam("customField") String customField,
            @RequestParam("files") MultipartFile[] uploadfiles) {

        // Get file name
        String uploadedFileName = Arrays.stream(uploadfiles)
        								.map(x -> x.getOriginalFilename())
        								.filter(x -> !StringUtils.isEmpty(x))
        								.collect(Collectors.joining(" , "));

        if (StringUtils.isEmpty(uploadedFileName)) {
            return new ResponseEntity("파일을 선택하세요.", HttpStatus.OK);
        }

        try {
        	personService.saveUploadFiles(Arrays.asList(uploadfiles));
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity("업로드 성공 - " + uploadedFileName, HttpStatus.OK);

    }

	/**
	 * 모델로 멀티파일 업로드
	 */
    @PostMapping("/upload/multi/model")
    public ResponseEntity<?> multiUploadFileModel(@ModelAttribute UploadModel model) {

        try {
        	personService.saveUploadFiles(Arrays.asList(model.getFiles()));
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity("Successfully uploaded!", HttpStatus.OK);
    }
}

PersonService.java

package com.gaeyou.firstproject.service;

import java.io.IOException;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;

import com.gaeyou.firstproject.model.PersonModel;

public interface PersonService {
	
	PersonModel getPerson();
	void saveUploadFiles(List<MultipartFile> files) throws IOException;
	
}

 

PersonServiceImpl.java

package com.gaeyou.firstproject.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.gaeyou.firstproject.dao.PersonDao;
import com.gaeyou.firstproject.model.PersonModel;
import com.gaeyou.firstproject.service.PersonService;

@Service
public class PersonServiceImpl implements PersonService {
	
	private static String UPLOADED_FOLDER = "./upload/";
	
	@Autowired
	private PersonDao personDao;
	
	@Override
	public PersonModel getPerson() {
		PersonModel person = personDao.getPerson();
		return person;
	}
	
	/**
	 * 파일 저장
	 */
	@Override
	public void saveUploadFiles(List<MultipartFile> files) throws IOException {
		for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
        }
	}
	
}

 

UploadModel.java

package com.gaeyou.firstproject.model;

import org.springframework.web.multipart.MultipartFile;

import lombok.Data;

@Data
public class UploadModel {
	
	private String extraField;
	private String customField;
	private MultipartFile[] files;
    
}

 

 

resources/static/upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <h1>파일 업로드</h1>
    
    <form method="POST" enctype="multipart/form-data" id="fileUploadForm">
        <input type="text" name="extraField"/><br/><br/>
        <input type="file" name="files"/><br/><br/>
        <input type="file" name="files"/><br/><br/>
        <input type="submit" value="Submit" id="btnSubmit"/>
    </form>
    
    <h1>결과</h1>
    <pre>
        <span id="result"></span>
    </pre>
    
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
    
</body>
</html>

resources/static/js/main.js

$(document).ready(function () {
    $('#btnSubmit').click(function (event) {
        event.preventDefault();
        
        var form = $('#fileUploadForm')[0];
        var data = new FormData(form);
        data.append('customField', '추가필드');
        $('#btnSubmit').prop('disabled', true);

        $.ajax({
            type: 'POST',
            enctype: 'multipart/form-data',
            url: '/persons/upload/multi',
            data: data,
            processData: false,
            contentType: false,
            cache: false,
            timeout: 600000,
            success: function (data) {
                $('#result').text(data);
                console.log('SUCCESS : ', data);
                $('#btnSubmit').prop('disabled', false);
            },
            error: function (e) {
                $('#result').text(e.responseText);
                console.log('ERROR : ', e);
                $('#btnSubmit').prop('disabled', false);
            }
        });
        
    });
});

 

서버구동

서버를 구동하고 브라우저로 접속해서 파일을 업로드 해봅니다.

hello text라는 extraField와 파일 두개가 업로드 되었습니다.

 

프로젝트 폴더 전체 구조는 위와 같습니다.

upload 폴더에 파일이 두개 올라간것을 확인할 수 있습니다.

 

 

Spring Boot / Oracle / Mybatis 차례

반응형
Comments