티스토리 뷰

어제 업로드에 이어 다운로드입니다.

 

dependency는 https://cusonar.tistory.com/45 글을 참조해주세요.

 

ID는 파일명입니다. 업로드에서 UUID 형식으로 파일을 저장했으므로 UUID를 ID에 넣어주시면 됩니다.

FileController.java
@RestController
@RequestMapping("/files")
@Slf4j
public class FileController {
	
	@Value("${temp.path}") private String tempPath;
	
	@GetMapping("/{id}")
	public Resource download(@PathVariable String id) throws IOException {
		File file = new File(tempPath + id);
		InputStream is = FileUtils.openInputStream(file);
		return new InputStreamResource(is);
	}
}

 

cURL 테스트
curl -o test.txt -X GET http://localhost:8080/files/test

 

Pure Javascript 테스트
<!DOCTYPE html>
<html>
<head>
	<script>
		function download(filename) {
			// var token = localStorage.getItem('X-Auth-Token');
			var xhttp = new XMLHttpRequest();
			xhttp.onreadystatechange = function() {
			  var a;
			  if (xhttp.readyState === 4 && xhttp.status === 200) {
				if (typeof window.navigator.msSaveBlob !== 'undefined') {
				  window.navigator.msSaveBlob(xhttp.response, filename);
				} else {
				  a = document.createElement('a');
				  a.href = window.URL.createObjectURL(xhttp.response);
				  a.download = filename;
				  a.style.display = 'none';
				  document.body.appendChild(a);
				  a.click();
				}
			  } else if (xhttp.readyState === 4) {
				var reader = new FileReader();
				reader.addEventListener('loadend', (e) => {
				  var errorMessage = JSON.parse(e.srcElement['result']);
				  log.error(errorMessage);
				});
				reader.readAsText(xhttp.response);
				this.loading = false;
			  }
			};
			xhttp.open('GET', 'http://localhost:8080/files/test');
			// xhttp.setRequestHeader('X-Auth-Token', `${token}`);
			xhttp.responseType = 'blob';
			xhttp.send();
		}
	</script>
</head>
	
<body>
	<button onclick="download('test.txt')">Download</button>
</body>
</html>

주석 부분을 제외하시면 X-Auth-Token 헤더에 token을 추가해서 요청을 할 수 있습니다. 일반적으로 인증이 불필요하면a 태그를 통해 바로 처리하셔도 됩니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함