[Spring Boot] 쓰기싫은 Jquery로 파일 업로드 구현

exoluse·2021년 12월 8일
0

Spring

목록 보기
2/11
post-thumbnail

1. maven dependency check

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. application.properties

spring.resources.static-locations = classpath:/static/,file:////Users/exoluse/dev/java/newProject/

3. 업로드 폴더 만들기

cd /Users/exoluse/dev/java/newProject/
mkdir uploadFile

4. upload page

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
	<head>
		<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
		<script>
		
			function uploadFileSetup(obj){
				
				// file size 미리 체크.
				if(1024768*10 < obj.files[0].size) {
					console.log("NO!!!", obj.files[0].size);
					return;
				}
				
				/*
				if(obj.files[0].name.split('.').pop() == "png") {
					console.log("NO!!!PNG!!!", obj.files[0].name);
					return;					
				}
				*/
								
				var data = new FormData()
				data.append('file', obj.files[0])
				
				fetch('/upload', {
				  method: 'POST',
				  body: data
				}).then(
					(response) => { 
						
						if(response.status == "200") {
							// blahblah~
						} else {
							// console.log("~~~~~~~~~~~~~")
						}
					} 
				).catch((exception) => {
					console.log(exception);
				})
			}
		
			$(function() {
	    
		        $("input[type='file']").change(function(){
		            uploadFileSetup(this);
		        });
				
			});
		</script>
	</head>
	
	<body>
		<input type="file" id="aaa" />
	</body>
</html>

5. controller

귀찮아서 서비스를 만들지는 않는다.

package com.iut.mes.asset.controller;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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
public class AssetController {
	

  public static final String folderPath =  "/Users/exoluse/dev/java/newProject/uploadFile/";
  public static final Path filePath = Paths.get(folderPath);

	@RequestMapping(value="/index")
	public String index() {
		return "index";
	}
	
	
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
        	
            createDirIfNotExist();

            byte[] bytes = new byte[0];
            bytes = file.getBytes();
            Files.write(Paths.get(folderPath + file.getOriginalFilename()), bytes);
            return ResponseEntity.status(HttpStatus.OK).body("Files uploaded successfully: " + file.getOriginalFilename());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body("Exception occurred for: " + file.getOriginalFilename() + "!");
        }
    }

    

    /**
     * make folder
     */
    private void createDirIfNotExist() {
        //create directory to save the files
        File directory = new File(folderPath);
        if (!directory.exists()) {
            directory.mkdir();
        }
    }    
}

6. 업로드 테스트

파일을 바꾸면 바로 파일이 업로드 된다.

7. 파일 다운로드 요청 추가

package com.iut.mes.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
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
public class FileController {
	

  public static final String folderPath =  "D:/dev/java/uploadFile";
  public static final Path filePath = Paths.get(folderPath);

	@RequestMapping(value="/uploadForm")
	public String uploadForm() {
		return "uploadForm.web";
	}
	
	
    @PostMapping("/fileUpload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
        	
            createDirIfNotExist();

            byte[] bytes = new byte[0];
            bytes = file.getBytes();
            Files.write(Paths.get(folderPath + File.separator + file.getOriginalFilename()), bytes);
            return ResponseEntity.status(HttpStatus.OK).body("Files uploaded successfully: " + file.getOriginalFilename());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body("Exception occurred for: " + file.getOriginalFilename() + "!");
        }
    }

    

    /**
     * make folder
     */
    private void createDirIfNotExist() {
        //create directory to save the files
        File directory = new File(folderPath);
        if (!directory.exists()) {
            directory.mkdir();
        }
    }


    @RequestMapping("/fileDownload")
	public ResponseEntity<InputStreamResource> download(@RequestParam String pFileName) throws IOException {
		
		// 파일 경로 
		String path = folderPath + File.separator + pFileName;
		
		File file = new File(path);
		
		// 파일 존재 유무 
		boolean fExist = file.exists();
		
		if(fExist) {
	        
	        String fileName = file.getName();
	        
	        HttpHeaders header = new HttpHeaders();
	        header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName);
	        header.add("Cache-Control", "no-cache, no-store, must-revalidate");
	        header.add("Pragma", "no-cache");
	        header.add("Expires", "0");
	        
	        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
	        
	        return ResponseEntity.ok()
	                .headers(header)
	                .contentLength(file.length())
	                .contentType(MediaType.parseMediaType("application/octet-stream"))
	                .body(resource);
		}
		return null;
	}

8. 다운로드 테스트

0개의 댓글