티스토리 뷰

728x90
반응형

개발 환경

java version "21.0.4" 2024-07-16 LTS
Java(TM) SE Runtime Environment (build 21.0.4+8-LTS-274)
Java HotSpot(TM) 64-Bit Server VM (build 21.0.4+8-LTS-274, mixed mode, sharing)

 

Tomcat v10.1

 

사전 정보

Tomcat v10.1 에서 "Commons FileUpload" 를 사용하는 경우 다음과 같은 오류가 지속적으로 발생했다.

 

The type javax.servlet.http.HttpServletRequest cannot be resolved. 

It is indirectly referenced from required type org.apache.commons.fileupload.servlet.ServletFileUpload

The method parseRequest(HttpServletRequest) from the type ServletFileUpload refers to the missing type HttpServletRequest

 

원인은?

Tomcat v10.1 은 "jakarta.servlet.http.HttpServletRequest" 사용하는 반면

Commons FileUpload.jar 는 "javax.servlet.http.HttpServletRequest" 을 사용하기 때문에 "upload.parseRequest(request)" 에서 오류가 발생한다.

ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List<FileItem> formItems = upload.parseRequest(request);



tomcat v10.1 사용시 발생하는 오류인데 어떻게 해결해야 하지?

아래 3개의 파일을 WEB-INF -> lib 폴더에 추가하고 코드를 수정했다.

commons-fileupload2-jakarta-servlet6-2.0.0-M2.jar
0.01MB
commons-io-2.16.1.jar
0.49MB
commons-fileupload2-core-2.0.0-M2.jar
0.06MB

 

fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File Upload</title>
</head>
<body>
	<form name="fileUploadForm" action="fileUpload.do" method="post" encType="multipart/form-data">
		<p>
			파일1: <input type="file" name="file1" />
		</p>
		<p>
			파일2: <input type="file" name="file2" />
		</p>
		
		<input type="submit" value="Data Send" />
	</form>
</body>
</html>

 

fileUpload.servlet

package jspFileManager.ex1;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;

import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.core.FileItem;
import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet(
    name = "UploadServlet",
    urlPatterns = {"/fileUpload.do"}
)
public class FileUploadServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (JakartaServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory factory = DiskFileItemFactory.builder().get();
            
            JakartaServletFileUpload upload = new JakartaServletFileUpload(factory);
            upload.setFileSizeMax(1024*1024);
            upload.setSizeMax(1024*1024);
        
            String uploadPath = "/Users/jeonghun/eclipse-workspace/uploadedFiles";
            
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            
            try {
                List<FileItem> formItems = upload.parseRequest(request);
                if (formItems != null && formItems.size() > 0) {
                    for (FileItem item : formItems) {
                        if (!item.isFormField()) {
                            String fileName = new File(item.getName()).getName();
                            item.write(Path.of(uploadPath, fileName));
                            
                            response.getWriter().println(String.format(
                            		"Filed Name = %s, File Name = %s, File Size = %s "
                            		, item.getFieldName()
                            		, item.getName()
                            		, item.getSize()
                    		));
                        }
                    }
                }
            } catch (Exception ex) {
               System.out.println("There was an error: " + ex.getMessage());
            }
        }
    }
}

 

 

fileDownload.java

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    isELIgnored="false"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<img src="${ pageContext.request.contextPath }/fileDownload.do?fileName=Designer (30).jpeg" width="500" height="500" />
	<br>
	<a href="${ pageContext.request.contextPath }/fileDownload.do?fileName=Designer (30).jpeg"> file download</a>
</body>
</html>

 

 

fileDownload.servlet

package jspFileManager.ex1;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/fileDownload.do")
public class fileDownloadServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doHandle(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doHandle(req, resp);
	}
	
	protected void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String file_repo = "/Users/jangjeonghun/eclipse-workspace/uploadedFiles";
		String fileName = "Designer (30).jpeg";
		String downloadFileFullPath = String.format("%s/%s", file_repo, fileName);
		
		ServletOutputStream outputStream = response.getOutputStream();
		File file = new File(downloadFileFullPath);
		
		response.setHeader("Cache-Control", "no-cache");
		response.addHeader("Content-disposition", "attachment; fileName="+fileName);
		
		FileInputStream fileInputStream = new FileInputStream(file);
		byte[] buffer = new byte[1024*8];
		
		while(true) {
			int count = fileInputStream.read(buffer);
			
			if(count == -1) { break; }
			outputStream.write(buffer, 0, count);
		}
		
		fileInputStream.close();
		outputStream.close();
	}

}

 

 

추가 정보

728x90
반응형