개발을 진행하면서 이미지나 동영상 등등 업로드 관련은 사용자가 input file 값을 같이 서버에 요청해서 서버는 그 값을 받아 Commons-fileupload 라이브러리를 이용해 서버에 업로드를 하고 디비에는 경로만 저장하는 방식을 사용했다. 그래서 디비에 파일 자체를 업로드를 할 수 있다는 것을 몰랐다. 이번에 서버에서 다른 서버로 파일을 옮겨야 하는 상황이 생겨서 처음에는 FTP 라이브러리를 이용하다가 보안상으로 사용을 못 하고 고민하다가 디비에다가 넣어서 받을 수 있다는 것을 알게 되어 찾아보니 파일을 Byte 단위로 쪼개서 BLOB으로 넣을 수 있다는 것을 알게 되었다.
Source Insert Upload Input
public int pdfFileInsert() throws Exception {
HashMap<String, Object> pdfFileMap = new HashMap<String, Object>();
FileInputStream pdfFileInput = null;
ByteArrayOutputStream pdfOutput = null;
File pdfFile = new File("C:\\SpingBoot입문과활용.pdf");
int pdfInsertCheck = 0;
int read = 0;
byte[] buf = new byte[3072];
byte[] redBuf = null;
try {
if(!pdfFile.exists())
throw new FileNotFoundException("파일이 없습니다.");
pdfFileInput = new FileInputStream(pdfFile);
pdfOutput = new ByteArrayOutputStream();
while((read = pdfFileInput.read(buf,0, buf.length)) != -1) {
pdfOutput.write(buf,0,read);
}
redBuf = pdfOutput.toByteArray();
pdfFileMap.put("fileName", "SpingBoot입문과활용.pdf");
pdfFileMap.put("filePdf", redBuf);
pdfInsertCheck = mainMapper.insertpdfFile(pdfFileMap);
if(pdfInsertCheck <= 0)
throw new Exception();
}finally {
if(pdfFileInput != null)
pdfFileInput.close();
if(pdfOutput != null)
pdfOutput.close();
}
return pdfInsertCheck;
}
Source Select Download Output
public void getPdfFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
Map<String, Object> map = mainMapper.getPdfFile();
String fileName = (String) map.get("FILE_NAME");
Blob blob = (Blob) map.get("FILE_PDF");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("UTF-8"),"ISO-8859-1"));
bis = new BufferedInputStream(blob.getBinaryStream());
bos = new BufferedOutputStream(response.getOutputStream());
int read = 0;
byte[] buf = new byte[3072];
while((read = bis.read(buf)) != -1) {
bos.write(buf,0, read);
}
}finally {
if(bis != null)
bis.close();
if(bos != null)
bos.close();
}
}
'낙서장 > Spring' 카테고리의 다른 글
[url mapping pattern] /* /** 차이 (0) | 2021.10.13 |
---|---|
Spring PDF 파일 ResponseEntity로 보여주기 (0) | 2021.09.23 |
Spring 다른 서버에 파일 보내기(FTP) (0) | 2021.09.07 |
Spring Project Setting (0) | 2021.08.19 |
Spring @Scheduled (0) | 2021.08.12 |