티스토리 뷰
반응형
Java에서 특정 파일의 URL 주소를 읽어 수신자의 브라우저 상에서 파일이 다운로드되고싶다면,
1. Response를 Setting한다.
application/octet-stream
response.setContentType("application/octet-stream"); //8bit(=1Byte) 단위의 binary data라는 의미
String headerKey = "Content-Disposition"; // 수신받은 브라우저가 파일명을 지정
String headerValue = "attachment; filename=" + "다운받을파일명.jpg";
response.setHeader(headerKey, headerValue);
2. 파일을 Stream으로 읽어들인다.
String url = "https://~~~~~~~~~a7a63c.jpg";
InputStream inputStream = URI.create(url).toURL().openStream();
InputStream vs BufferedInputStream
3. InputStream을 BufferedInputStream으로 바꿔준다.
InputStream의 경우 최상위 Stream을 읽는데 사용되는 객체로
BuffredInputStream으로 사용할 경우 InputStream보다 속도가 빠르다
BufferedInputStream fin = null;
BufferedOutputStream outs = null;
fin = new BufferedInputStream(inputStream);
outs = new BufferedOutputStream(response.getOutputStream());
int BUFFER_SIZE = 8192; // 8kb = 8*1024 (Byte)
int read = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while ((read = bInputStream.read(buffer)) != -1) { //input
boutputStream.write(buffer, 0, read);
}
만약 28KB의 파일을 읽어들인다고 한다면,
해당 코드를 실행한 모습을 확인하면 다음과 같다.
BUFFER_SIZE를 8KB(=8192=810241024*1Byte)로 설정을 해놓았기아
1Byte는 -127~128까지 총 256(2^8)을 가져오고 있으며
28KB이기에 8KB씩 읽어들이므로 4번찍힘을 확인할 수 있다.
8192
[B@7dbae40
7959
[B@7dbae40
8192
[B@7dbae40
3423
[B@7dbae40
@GetMapping("/test")
public void testdownload(HttpServletResponse response){
try {
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=" + "다운받을파일명.jpg";
response.setHeader(headerKey, headerValue);
String url = "https://~~~~~~~~~a7a63c.jpg";
InputStream inputStream = URI.create(url).toURL().openStream();
BufferedInputStream bInputStream = null;
BufferedOutputStream boutputStream = null;
bInputStream = new BufferedInputStream(inputStream);
boutputStream = new BufferedOutputStream(response.getOutputStream());
int BUFFER_SIZE = 8192; // 8kb = 8*1024 (Byte)
int read = 0;
byte[] buffer = new byte[BUFFER_SIZE];
while ((read = bInputStream.read(buffer)) != -1) {
boutputStream.write(buffer, 0, read);
}
} catch ( Exception e){
e.printStackTrace();
}
}
응답받을 response를 다운로드하기
blob은 binary large object의 약자입니다.
이름처럼 바이너리 형태로 큰 객체를 저장하며 이미지, 비디오 등 멀티미디어 객체를 나타냅니다.
한 가지 유의해야 할 점은 Blob 또는 파일 자체는 사실 데이터 자체라기보다는
데이터를 간접적으로 접근하기 위한 포인터 객체입니다.
JS에서 new File()객체는 Blob을 상속받았습니다
async fileDownload(index) {
try {
// const fileUrl = this.selectItem.files[index]
// const response = await this.$axios.get(`${this.$config.IMAGE_SERVER_URL}/${fileUrl}`, {
const response = await this.$axios.get(`/api/ipcc/counsel/know/test`, {
responseType: 'blob',
})
const blob = new Blob([response.data])
const fileObjectUrl = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.href = fileObjectUrl
link.style.display = 'display'
link.download = this.extractFilenameByResponse(response)
document.body.appendChild(link)
link.click()
link.remove()
window.URL.revokeObjectURL(fileObjectUrl)
} catch (error) {}
반응형
'java_basic' 카테고리의 다른 글
Build 패턴 NullPointException, ArrayList (0) | 2023.06.10 |
---|---|
람다와 익명클래스는 람다가 정의된 메서드의 지역변수의 값은 바꿀 수 없다 (1) | 2023.03.11 |
Lambda 기초5 최종연산 reduce (0) | 2022.02.16 |
Lambda 기초4 중간연산2 (0) | 2022.02.16 |
Lambda 기초4 중간연산1 (2) | 2022.02.14 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- java
- 최종연산
- lambda
- install
- AnnotationConfigApplicationContext
- Intellij
- Vue
- MAC
- ApplicationContext
- 스트림
- 람다
- JPA
- webpack
- mvn
- docker
- 중간연산
- 영속성 컨텍스트
- BeanFactory
- elasticsearch
- 차이
- Vuex
- springboot
- vscode
- stream
- ngnix
- 자바8
- nginx
- NPM
- container
- map
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함