HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🤩
개발
/
Spring
Spring
/
파일 업로드 & 다운로드

파일 업로드 & 다운로드

[ 블로그 ] Spring- MVC 파일 다운로드
File Upload through httpFile Upload(Raw data upload)File Download(Raw data download)브라우저에서 파일 다운받기

File Upload through http

file upload를 HTTP 와 REST 어플리케이션에서 수행되는 방식은 아래 두가지 방법이 있음
  • Multi-part Forms
  • Raw Data Uploads

File Upload(Raw data upload)

Content-Type: application/octet-stream
브라우저에서 바로 다운받는식으로 하려면 ContentDisposition을 이용해서 데이터 반환해주어야 함
curl http://localhost:8080/assets/upload\?path\=testfolder1/testfolder2/ohho.pdf --request POST --data-binary "@test.pdf" -H "Content-Type:application/octet-stream" -i
@PostMapping("/upload") public ApiResponse<AssetUploadResponse> uploadFile(@RequestParam String path, @RequestBody byte[] data) { assetService.upload(path, data); return ApiResponse.ok(List.of(new AssetUploadResponse(path))); }

File Download(Raw data download)

@GetMapping("/download") public ResponseEntity<byte[]> downloadAsset(@RequestParam String path) { byte[] downloadedFile = assetService.download(path); return ResponseEntity.ok(downloadedFile); }
curl http://localhost:8080/assets/download\ ?path\=testfolder1/testfolder2/ohho.pdf --request GET -i > test.pdf
download API 호출 후 byte array를 test.pdf에 쓰기

브라우저에서 파일 다운받기

@GetMapping("/download/img") public ResponseEntity<Resource> downloadImg() { return ResponseEntity.ok() .contentType(MediaType.IMAGE_PNG) // (3) .header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline() // (4) .filename(SAMPLE_FILE_NAME, StandardCharsets.UTF_8) .build() .toString()) .body(resource); }
axios를 이용하여 해당 api 호출 시 ContentDisposition 헤더가 포함되지 않는 이슈가 있었음
Response Headers의 Content-Disposition 항목이 없는 이슈
Axios expose Response headers : Content-Disposition
@RestController @RequestMapping("/api/files") @CrossOrigin(value = {"*"}, exposedHeaders = {"Content-Disposition"}) public class FileBoundary { // code ... }
  • 서버 측에서 @CrossOrigin 설정을 적용해주어야 axios에서 해당 헤더에 접근이 가능함. Response에 포함되어 있어도 axios에서 못받음 해당 설정이 없으면
axios에서 request 옵션으로 responseType : “arraybuffer” 명시해주어야 파일이 깨지지 않음
[Axios Docs ] axios request config
github issue