인터페이스 7일차 (파일업로드, 다운로드, 이미지 출력)
2023. 1. 11. 12:28ㆍ코딩배움일지/인터페이스 구현
파일 업로드
spring.servlet.multipart.max-file-size=100MB 파일 보낼때 최대 용량은 100MB
spring.servlet.multipart.max-request-size=150MB 리퀘스트 자체의 용량은 150MB이다.
server.port=4040
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/board?serverTimezone=UTC&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=150MB
file.dir=C:/fileupload/
추가해주고 작동시켜서 오류확인
File Controller
package com.jingu.board.controller;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.jingu.board.service.FileService;
@RestController
@RequestMapping("file/")
public class FileController {
@Autowired FileService fileService;
// 파일을 서버에 업로드. Upload file to Server 서버로 가는거다. post
@PostMapping("upload")
//post는 requestbody 에서 받는다.전체로 받을때 body 분리는 param
//@RequestParm(file명) : RequestBody에서 특정 필드를 받아옴. 파일을 MultipartFile 받는다.
// Request body 에 파일을 받아 올땐 MultiparFile 인스턴스로 받음
public String fileUpload(@RequestParam("file") MultipartFile file) {
return fileService.fileUpload(file);
}
// 파일을 서버에서 다운로드 Download File from Server 서버에서 가져오는거다 Get
//@GetMapping("download")
// 이미지파일일 경우 이미지를 출력 if file is ImgFile printout image in Screen
//@GetMapping("")
}
File Service
package com.jingu.board.service;
import java.io.File;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
@Service
public class FileService {
// 환경변수(application.properties) 의 값
@Value("${file.dir}")
private String dir;
// 파일 업로드 서비스
public String fileUpload(MultipartFile file) {
//file 이 있는지 검사
if(file.isEmpty()) return null;
// Get Original File name
String originalFileName = file.getOriginalFilename();
// 확장자를 가져옴 file extension 이미지라면 (img.png)
String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
// 저장할 때 이름으로 사용되는 UUID 생성 //파일명 중복을 피하기위해서 RandoUUID
String uuid = UUID.randomUUID().toString();
// 실제로 저장되는 이름 생성
String saveName = uuid + extension;
// 파일이 저장된 실제 경로
String savePath = dir + saveName;
// 해당 파일을 실제로 저장
try {
file.transferTo(new File(dir + saveName));
} catch (Exception e) {
return null;
}
return saveName;
}
}
이미지 출력
파일서비스 에 추가
// 이미지 출력 path value 로 받을거다.
public Resource getImage(String imageName) {
try {
return new UrlResource("file:" + dir + imageName);
} catch (Exception e) {
return null;
}
}
파일 컨트롤러 추가
// 이미지파일일 경우 이미지를 출력 if file is ImgFile printout image in Screen
@GetMapping(value = "image/{imageName}", produces = {MediaType.IMAGE_PNG_VALUE,MediaType.IMAGE_JPEG_VALUE})
public Resource getImage(@PathVariable("imageName")String imageName) {
return fileService.getImage(imageName);
}
파일 다운로드
파일서비스 추가
// 파일 다운로드
public Resource fileDownload(String fileName) {
try {
return new UrlResource("file:" + dir + fileName);
} catch (Exception e) {
return null;
}
}
파일컨트롤러 추가
// 파일을 서버에서 다운로드 Download File from Server 서버에서 가져오는거다 Get
@GetMapping("download/{fileName}")
//ResponseEntity 컨트롤 해준다.
public ResponseEntity<Resource> fileDownload(@PathVariable("fileName") String fileName){
return ResponseEntity
.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
.body(fileService.fileDownload(fileName));
}
'코딩배움일지 > 인터페이스 구현' 카테고리의 다른 글
인터페이스 8일차 (데이터베이스에 등록된 모든 정보 출력) (0) | 2023.01.12 |
---|---|
인터페이스 7일차 (Delete) (0) | 2023.01.11 |
인터페이스 7일차 (Update) (0) | 2023.01.11 |
인터페이스 6일차 (회원가입 및 중복여부확인 Create, Read) (0) | 2023.01.10 |
인터페이스 5일차(Repository) (0) | 2023.01.09 |