파일 업로드 및 다운로드 구현하기 (with React)
태그: React
카테고리: Spring
업데이트:
application.properties 설정하기
최대 파일 사이즈를 20MB로 지정
spring.servlet.multipart.max-file-size:20MB
파일 업로드 구현하기
Controller 구현
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.multipart.dto.FoodDto;
@RestController
@RequestMapping("/file")
public class MultipartController {
@PostMapping("/upload")
public ResponseEntity<Object> uploadFiles(MultipartFile[] multipartFiles) { // 파라미터의 이름은 client의 formData key값과 동일해야함
String UPLOAD_PATH = "/Project/Files"; // 업로드 할 위치
try {
for (int i = 0; i < multipartFiles.length; i++) {
MultipartFile file = multipartFiles[i];
// 현재 날짜와 랜덤 정수값으로 새로운 파일명 만들기
String fileId = (new Date().getTime()) + "" + (new Random().ints(1000, 9999).findAny().getAsInt());
String originName = file.getOriginalFilename(); // 파일 이름 추출 (image.jpg)
String fileExtension = originName.substring(originName.lastIndexOf(".") + 1); // 파일 확장자 추출
originName = originName.substring(0, originName.lastIndexOf(".")); // 확장자를 제거한 파일 이름 추출
long fileSize = file.getSize(); // 파일 사이즈
File fileSave = new File(UPLOAD_PATH, fileId + "." + fileExtension); // 새로운 파일명.확장자로 파일 생성
if (!fileSave.exists()) { // 디렉터리가 없는 경우 새로운 디렉터리 생성
fileSave.mkdirs();
}
file.transferTo(fileSave); // fileSave의 형태로 파일 저장
System.out.println("파일 생성 완료")
}
} catch (IOException e) {
return new ResponseEntity<Object>(null, HttpStatus.CONFLICT);
}
return new ResponseEntity<Object>("Success", HttpStatus.OK);
}
}
React 코드 구현
import React, {useState} from 'react';
import axios from 'axios';
function FileUpload() {
const [fileList, setFileList] = useState([]);
function onSaveFiles(e) {
const uploadFiles = Array.prototype.slice.call(e.target.files); // 파일선택창에서 선택한 파일들
let newFileList = []
uploadFiles.forEach((uploadFile) => {
newFileList.push(uploadFile);
});
setFileList(newFileList)
};
function onFileUpload () {
const formData = new FormData();
fileList.forEach((file) => {
formData.append('multipartFiles', file); // 파일 데이터 저장
});
// 또 다른 Param을 넘기고 싶으면 다음과 같이 직렬화해 객체로 저장
// formData.append('uploader', JSON.stringify(uploader));
axios.post('http://localhost:8080/file/upload', formData);
};
return (
<div>
<input type="file" multiple /* 파일 여러개 선택 가능하게 하기 */ onChange={onSaveFiles}/>
<button onClick={onFileUpload}>파일 업로드</button>
</div>
);
};
export default FileUpload;
파일 다운로드 구현
Controller 구현
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/file")
public class FileController {
@GetMapping("/download")
public ResponseEntity<Object> download() {
String UPLOAD_PATH = "/Project/Files"; // 업로드 할 위치
String PATH = UPLOAD_PATH + "/jarzip.PNG";
try {
Path filePath = Paths.get(PATH);
Resource resource = new InputStreamResource(Files.newInputStream(filePath)); // 파일 resource 얻기
File file = new File(path);
HttpHeaders headers = new HttpHeaders();
// 다운로드 되거나 로컬에 저장되는 용도로 쓰이는지를 알려주는 헤더
headers.setContentDisposition(ContentDisposition.builder("attachment").filename(file.getName()).build());
return new ResponseEntity<Object>(resource, headers, HttpStatus.OK);
} catch(Exception e) {
return new ResponseEntity<Object>(null, HttpStatus.CONFLICT);
}
}
}
React 코드 구현
import React, {useState, useEffect} from 'react';
function FildDownload() {
return (
<div>
<a href="http://localhost:8080/file/download"> File Download </a>
</div>
)
}
댓글남기기