Spring

파일 업로드, 다운로드

wintertreey 2024. 8. 13. 17:39

css나 이미지는 static폴더 내에 위치해야한다.

 

이미지 파일 사이즈 제한주기.

 

 

++

 

자동으로 refresh되도록 체크해두자

 

 

파일업로드

package pack.controller;

import org.springframework.web.multipart.MultipartFile;

import lombok.Data;

@Data
public class UploadDto {
	private String myName;
	private MultipartFile myFile;
	//등록일 등 기타는 생략
}
package pack.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import lombok.Data;

@Data
@Component
public class UploadFile {
	private MultipartFile file;
}

 

 

그럼 controller 작업으로 연동해보자

폼작업

package pack.controller;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import lombok.Data;

@Data
@Component
public class UploadFile {
	private MultipartFile file;
}

 

<body>
<form action="upload" method="post" enctype="multipart/form-data">
업로드할 파일 선택 : <input type="file" name="file"><p/>
<input type="submit" value="업로드 확인">
</form>
</body>

 

폼에서 파일업로드작업

@PostMapping("upload")
	public String submit(UploadFile uploadFile, Model model, BindingResult result) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		
		//업로드된 파일 검사
		MultipartFile file = uploadFile.getFile();
		String fileName = file.getOriginalFilename();
		
		if(result.hasErrors()) {
			return "error";
		}
		
		try {
			inputStream = file.getInputStream();
			File newFile = new File("C:\\work2\\sprsou\\sprweb24fileupload\\src\\main\\resources\\static\\upload\\"+ fileName); //절대경로
			if(!newFile.exists()) {
				newFile.createNewFile();
			}
			outputStream = new FileOutputStream(newFile);
			int read = 0;
			byte[] bytes = new byte[1024];
			while((read = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}
		} catch (Exception e) {
			System.out.println("file submit err: "+e);
			return "error";
		}finally {
			try {
				inputStream.close();
				outputStream.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		model.addAttribute("filename", fileName);
		return "uploadfile";
	}
<body>
<h3>업로드된 파일 정보</h3>
파일명: [[${filename}]]
</body>

upload 폴더 안에 업로드 된걸 확인할 수 있다.


다운로드

<input type="hidden" name="filename" th:value="${filename}">
<input type="submit" value="다운로드">
</form>
package pack.controller;

import java.io.File;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletResponse;

@Controller
public class DownloadController {
	@PostMapping("download")
	@ResponseBody
	public byte[] downProcess(HttpServletResponse response, 
			@RequestParam("filename") String filename) throws Exception{
		System.out.println("filename:"+ filename);
		
		File file = new File("C:\\work2\\sprsou\\sprweb24fileupload\\src\\main\\resources\\static\\upload\\"+ filename); //절대경로
		
		byte[] bytes = FileCopyUtils.copyToByteArray(file);
		String fn = new String(file.getName().getBytes(), "iso_8859_1");
		
		//브라우저에게 다운로드를 지시
		response.setHeader("Content-Disposition", "attachment;filename= \"" + fn + "\"");
		response.setContentLength(bytes.length);
		
		return bytes;
	}

}

이렇게 파일이 다운받아지는것을 확인할 수 있다.