Note > 스프링 부트 파일첨부, Ui Dropzone.js스프링부트 파일 첨부 처리 부분By a3040, Published on Invalid Date
Controller 작성
@Controller
public class FileUploadController {
...
@Autowired
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@PostMapping("/common/fileform/upload")
@ResponseBody
public ResponseEntity<List<Attachment>> uploadFiles(@RequestParam("file") List<MultipartFile> files) {
int owner_seq = 1;
List<Attachment> attachments = new ArrayList<Attachment>();
for (MultipartFile file : files) {
// 업로드된 파일 저장
try {
...
// 파일 정보 저장
storageService.store(file);
} catch (IOException e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
return ResponseEntity.ok(attachments);
}
파일첨부 저장을위한 서비스 부분
@Service
public class StorageService {
@Value("${upload.folder}")
private String uploadFolder;
private Path rootLocation;
public StorageService() {
this.rootLocation = null;
}
@PostConstruct
public void init() {
this.rootLocation = Paths.get(uploadFolder);
}
private String getExtension(MultipartFile file) {
String fileName = file.getOriginalFilename();
String fileExtension = "";
if (fileName != null && fileName.contains(".")) {
fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
}
return fileExtension;
}
void store(MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
String extension = this.getExtension(file);
String filename = UUID.randomUUID().toString() + "." + extension;
byte[] bytes = file.getBytes();
Path filePath = Paths.get(uploadFolder + File.separator + filename);
Files.write(filePath, bytes);
}
// Stream<Path> loadAll();
public Path load(String filename) {
return rootLocation.resolve(filename);
}
public Resource loadAsResource(String filename) throws MalformedURLException {
Path file = rootLocation.resolve(filename);
Resource resource = null;
resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
}
return resource;
}
public void delete(String filename) throws IOException {
Path file = load(filename);
Files.delete(file);
}
// void deleteAll();
}
설정을 위한 resources/application.properties 부분
upload.folder=C:\\Users\\H......3040\\upload
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB