[Java Server Pages] JSP 파일 업로드 & 다운로드 

 - GitHub




[내용 설명]


 1. 서블릿 3 파일 업로드

   1) MultipartConfig

· fileSizeThreshold: 파일이 디스크에 쓰여지는 사이즈를 지정할 수 있다. 크기 값은 바이트 단위(1024 * 1024 * 10 = 10MB)

· location: 파일이 기본적으로 저장되는 디렉토리, 기본값은 ""

· maxFileSize: 파일을 업로드할 수 있는 최대 크기, 값은 바이트 단위

· maxRequestSize: multipart/form-data 요청에 허용되는 최대 크기, 기본값은 무제한을 의미하는 -1L


   2) Part Interface

· Part 인터페이스는 miltipart/form-data POST 요청으로 수신받은 from 아이템이나 하나의 Part를 나타낸다.

· 몇가지 중요한 메서드는 getInputStream(), write(String fileName)으로 읽고 쓰는데 사용한다.


   3) HttpSerlvetRequest 변경사항

· HttpServletRequest에 getParts()메서드를 사용하여 multipart/form-data 방식으로 가져오는 모든 데이터를 가져올 수 있다.

· getPart(String partName)을 통해 필요한 내용만을 가져올 수도 있다.


[소스 코드]


1. JSP 파일 업로드 폼


<body>
<!-- 파일 전송 -->
<form action="UploadService" method ="post" enctype="multipart/form-data">
파일 : <input type = "file" name="fileName" />
<input type="submit" value="Upload" />
</form>
</body>
view raw gistfile1.txt hosted with ❤ by GitHub


2. Java 파일 업로드 기능


import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* fileSizeThreshold 서버로 파일을 저장할 때 파일의 임시 저장 사이즈
* maxFileSize 1개 파일에 대한 최대 사이즈
* maxRequestSize 서버로 전송되는 request의 최대 사이즈
* @author "SeokRae (kslbsh@gmail.com)"
* https://www.journaldev.com/2122/servlet-3-file-upload-multipartconfig-part
*/
@WebServlet("/UploadService")
@MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
maxFileSize=1024*1024*50, // 50 MB
maxRequestSize=1024*1024*100) // 100 MB
public class FileUpload extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -4793303100936264213L;
private static final String UPLOAD_DIR = "filefolder";
public FileUpload() {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 서버의 실제 경로
String applicationPath = request.getServletContext().getRealPath("");
String uploadFilePath = applicationPath + UPLOAD_DIR;
System.out.println(" LOG :: [서버 루트 경로] :: " + applicationPath);
System.out.println(" LOG :: [파일 저장 경로] :: " + uploadFilePath);
// creates the save directory if it does not exists
File fileSaveDir = new File(uploadFilePath);
// 파일 경로 없으면 생성
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
String fileName = null;
//Get all the parts from request and write it to the file on server
for (Part part : request.getParts()) {
getPartConfig(part);
fileName = getFileName(part);
System.out.println(" LOG :: [ 업로드 파일 경로 ] :: " + uploadFilePath + File.separator + fileName);
part.write(uploadFilePath + File.separator + fileName);
}
request.setAttribute("fileName", fileName);
getServletContext().getRequestDispatcher("/response.jsp").forward(request, response);
}
/**
* https://docs.oracle.com/javaee/6/api/javax/servlet/http/Part.html
*
* multipart/form-data 사용시 HttpServletRequest의 멤버 변수 중 Part의 형태로 전달됨
*
* @param part
*/
private void getPartConfig(Part part) {
System.out.println("------------------------------------------------------------");
System.out.println(" LOG :: [HTML태그의 폼태그 이름] :: " + part.getName());
System.out.println(" LOG :: [ 파일 사이즈 ] :: " + part.getSize());
for(String name : part.getHeaderNames()) {
System.out.println(" LOG :: HeaderName :: " + name + ", HeaderValue :: " + part.getHeader(name) + "\n");
}
System.out.println("------------------------------------------------------------");
}
/**
* Utility method to get file name from HTTP header content-disposition
*/
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
System.out.println(" LOG :: content-disposition 헤더 :: = "+contentDisp);
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
System.out.println(" LOG :: 파일 이름 :: " + token);
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


3. JSP 파일 업로드 결과 값 출력


<body>
<%-- Using JSP EL to get message attribute value from request scope --%>
<h2>${requestScope.fileName} File uploaded successfully!</h2>
파일명 : <a href = "FileDown?fileName=${requestScope.fileName }">${requestScope.fileName }</a>
</body>
view raw gistfile1.txt hosted with ❤ by GitHub


4. Java 파일 다운로드 기능


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/FileDown")
public class FileDown extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 4357653489057931185L;
public FileDown() {
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");
// 서버에 올라간 경로를 가져옴
ServletContext context = getServletContext();
String uploadFilePath = context.getRealPath("filefolder");
String filePath = uploadFilePath + File.separator + fileName;
System.out.println(" LOG [업로드된 파일 경로] :: " + uploadFilePath);
System.out.println(" LOG [파일 전체 경로] :: " + filePath);
byte[] b = new byte[4096];
FileInputStream fileInputStream = new FileInputStream(filePath);
String mimeType = getServletContext().getMimeType(filePath);
if(mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
// 파일명 UTF-8로 인코딩(한글일 경우를 대비)
String sEncoding = new String(fileName.getBytes("UTF-8"));
response.setHeader("Content-Disposition", "attachment; fileName= " + sEncoding);
// 파일 쓰기 OutputStream
ServletOutputStream servletOutStream = response.getOutputStream();
int read;
while((read = fileInputStream.read(b,0,b.length))!= -1){
servletOutStream.write(b,0,read);
}
servletOutStream.flush();
servletOutStream.close();
fileInputStream.close();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


'Basic > Jsp' 카테고리의 다른 글

[JSP 2.3 웹 프로그래밍 기초부터 중급까지] 정리  (2) 2017.10.21

JSP 내용 정리 - 트렐로



'Basic > Jsp' 카테고리의 다른 글

[Java Server Pages] 파일 업로드 & 다운로드  (1) 2018.12.12

+ Recent posts