Learning/JAVA
JSP 파일 업로드/다운로드 (전자정부 프레임워크)
monique
2022. 7. 8. 14:57
JSP
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div class="row justify-content-md-center">
<form:form enctype="multipart/form-data" id="fileUploadForm">
<table class="table table-bordered">
<tr>
<td>전자공고 제목 : <input type="text" id="title" name="title"><br></td>
</tr>
<tr>
<td>첨부파일 : <input type="file" id="uploadFile" name="uploadFile"></td>
</tr>
<tr>
<td>상태 : <span id="status"></span></td>
</tr>
</table>
<br>
<div style="text-align:right;">
<input type="button" value="게시" id="btnSubmit">
<input type="button" value="목록보기" onclick="location.href='../invest_board'">
</div>
</form:form>
</div>
<script>
$("#btnSubmit").click(function (event) {
event.preventDefault();
// Get form
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
// disabled the submit button
$("#btnSubmit").prop("disabled", true);
console.log(data.get("uploadFile"));
$.ajax({
type: "POST",
url: "/ir/investNotice",
/* enctype: 'multipart/form-data', */
data: data,
dataType: "text",
contentType : false,
processData : false,
success: function(data) {
console.log('통신 성공');
msg();
$("#btnSubmit").prop("disabled", false);
},
error: function(request, status, error) {
console.log("ERROR : "+request.status+"\n"+"message"+request.responseText+"\n"+"error:"+error);
$("#btnSubmit").prop("disabled", false);
alert("fail");
}
});
});
function msg(){
let msg = document.getElementById('status');
msg.innerHTML = "글쓰기 성공";
}
</script>
업로드 컨트롤러
private final String uploadDir = "C:/Users/INF/Desktop/SKI/upload/";
//String fileStorePath = EgovProperties.getProperty("Globals.fileStorePath");
@PostMapping("/ir/investNotice") //파일 업로드
public void write(Model model, InvestNoticeWrite inWrite) throws IOException {
//파일이름 생성/////////////
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Calendar dateTime = Calendar.getInstance();
String uniqueId = sdf.format(dateTime.getTime()) + "."
+ inWrite.getUploadFile().getOriginalFilename().substring(inWrite.getUploadFile().getOriginalFilename().lastIndexOf(".") + 1);
///////////////////////////
System.out.println("제목"+ inWrite.getTitle());
System.out.println("파일이름"+ uniqueId);
System.out.println("첨부파일 본이름"+ inWrite.getUploadFile().getOriginalFilename());
System.out.println("첨부파일 컨텐트 타입"+ inWrite.getUploadFile().getContentType());
System.out.println("첨부파일 크기"+ inWrite.getUploadFile().getSize());
System.out.println("첨부파일 바이트"+ inWrite.getUploadFile().getBytes());
System.out.println("확장자"+inWrite.getUploadFile().getOriginalFilename().substring(inWrite.getUploadFile().getOriginalFilename().lastIndexOf(".") + 1));
String realName = inWrite.getUploadFile().getOriginalFilename();
String contentType = inWrite.getUploadFile().getContentType();
String extension = inWrite.getUploadFile().getOriginalFilename().substring(inWrite.getUploadFile().getOriginalFilename().lastIndexOf(".") + 1);
long size = inWrite.getUploadFile().getSize();
inWrite.setFileContentType(contentType);
inWrite.setFilePath(uploadDir+uniqueId);
inWrite.setFileName(uniqueId);
inWrite.setFileRealName(realName);
inWrite.setFileSize(size);
inWrite.setFileExtension(extension);
//실제 폴더에 저장
if (!inWrite.getUploadFile().isEmpty()) {
String fullPath = uploadDir + uniqueId;
inWrite.getUploadFile().transferTo(new File(fullPath));
investNoticeService.write(inWrite);
}
}
다운로드 컨트롤러
@RequestMapping("/board/download/{attachUid}")
public void download(@PathVariable("attachUid") int attachUid, Model model, InvestNotice investNotice,
HttpServletRequest request, HttpServletResponse response) throws IOException {
InvestNotice one = investNoticeService.selectAllByUid(attachUid);
String header = request.getHeader("User-Agent");
String downloadFile = "C:/Users/INF/Desktop/SKI/upload/" + one.getInvestNoticeFile();
String downloadName = one.getInvestNoticeFile();//고유아이디
//파일명 일부만 가져와서 다운로드 이름 지정
String name = null;
String realName =null;
if(one.getFileRealName().length()<12) {
name = one.getFileRealName();
realName = name+"_"+downloadName;
}else {
name = one.getFileRealName().substring(0,12);
realName = name+"_"+downloadName;
}
System.out.println("경로"+downloadFile);
File file = new File(downloadFile);
//FileInputStream in = new FileInputStream(downloadFile);
long fileLength = file.length();
String typefile = request.getServletContext().getMimeType(file.toString());
System.out.println("---------------------테스트1"+typefile);
if(typefile==null) {
response.setContentType("application/octet-stream");
}
String downName = new String(realName.getBytes("euc-kr"), "ISO-8859-1");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + downName + "\";");
response.setHeader("Content-Transfer-Encoding", "binary");
//response.setHeader("Content-Type", "image/png; UTF-8");
response.setHeader("Content-Length", "" + fileLength);
response.setHeader("Pragma", "no-cache;");
response.setHeader("Expires", "-1;");
fileDownload(downloadFile, one.getFileSize(), response);
System.out.println("---------------------테스트2");
FileInputStream fileInputStream = new FileInputStream(file);
OutputStream os = response.getOutputStream();
os.flush();
os.close();
fileInputStream.close();
System.out.println("마지막까지 실행되는지 테스트");
}
public void fileDownload(String filePath, long fileSize, HttpServletResponse response){
try (FileInputStream fis = new FileInputStream(filePath)) {
OutputStream out = response.getOutputStream();
int readCount = 0;
byte[] buffer = new byte[Long.valueOf(fileSize).intValue()];
while ((readCount = fis.read(buffer)) != -1) {
out.write(buffer, 0, readCount);
}
} catch (Exception e) {
e.printStackTrace();
}
}
728x90