Computer >> 컴퓨터 >  >> 프로그램 작성 >> 프로그램 작성

JSP를 사용하여 어떻게 파일을 업로드할 수 있습니까?

<시간/>

JSP를 HTML 양식 태그와 함께 사용하면 사용자가 서버에 파일을 업로드할 수 있습니다. 업로드된 파일은 텍스트 파일, 바이너리, 이미지 파일 또는 모든 문서일 수 있습니다.

파일 업로드 양식 만들기

이제 파일 업로드 양식을 만드는 방법에 대해 알아보겠습니다. 다음 HTML 코드는 업로더 양식을 만듭니다. 다음은 메모해야 할 중요한 사항입니다 -

  • 양식 메서드 속성은 POST로 설정되어야 합니다. 메소드 및 GET 메소드는 사용할 수 없습니다.

  • enctype 형식 속성은 multipart/form-data로 설정되어야 합니다. .

  • 액션 형식 속성은 백엔드 서버에서 파일 업로드를 처리하는 JSP 파일로 설정되어야 합니다. 다음 예는 uploadFile.jsp를 사용하고 있습니다. 파일을 업로드할 프로그램 파일입니다.

  • 단일 파일을 업로드하려면 단일 을 사용해야 합니다. 유형 ="파일" 속성이 있는 태그 . 여러 파일 업로드를 허용하려면 이름 속성 값이 다른 두 개 이상의 입력 태그를 포함하십시오. 브라우저는 찾아보기 버튼을 각각에 연결합니다.

예시

<html>
   <head>
      <title>File Uploading Form</title>
   </head>
   <body>
      <h3>File Upload:</h3>
      Select a file to upload: <br />
      <form action = "UploadServlet" method = "post" enctype = "multipart/form-data">
         <input type = "file" name = "file" size = "50" />
          <br />
         <input type = "submit" value = "Upload File" />
      </form>
   </body>
</html>

그러면 다음 결과가 표시됩니다. 이제 로컬 PC에서 파일을 선택할 수 있으며 사용자가 "파일 업로드"를 클릭하면 선택한 파일과 함께 양식이 제출됩니다 -

출력

File Upload
Select a file to upload

참고 − 위의 형식은 더미 형식이며 작동하지 않습니다. 작동하려면 컴퓨터에서 위의 코드를 시도해야 합니다.

백엔드 JSP 스크립트 작성

이제 업로드된 파일이 저장될 위치를 정의하겠습니다. 프로그램에서 이것을 하드 코딩하거나 context-param과 같은 외부 구성을 사용하여 이 디렉토리 이름을 추가할 수도 있습니다. 다음과 같이 web.xml의 요소 -

<web-app>
   ....
   <context-param>
      <description>Location to store uploaded file</description>
      <param-name>file-upload</param-name>
      <param-value>
         c:\apache-tomcat-5.5.29\webapps\data\
      </param-value>
   </context-param>
   ....
</web-app>

다음은 UploadFile.jsp의 소스 코드입니다. . 이것은 한 번에 여러 파일의 업로드를 처리할 수 있습니다. 이제 파일 업로드를 진행하기 전에 다음 사항을 고려해 보겠습니다.

  • 다음 예는 FileUpload에 따라 다릅니다.; 최신 버전의 commons-fileupload.x.x.jar이 있는지 확인하세요. 클래스 경로에 있는 파일. https://commons.apache.org/fileupload/에서 다운로드할 수 있습니다.

  • FileUpload는 Commons IO에 따라 다릅니다. 최신 버전의 commons-io-x.x.jar이 있는지 확인하세요. 클래스 경로에 있는 파일. https://commons.apache.org/io/에서 다운로드할 수 있습니다.

  • 다음 예를 테스트하는 동안 maxFileSize보다 작은 크기의 파일을 업로드해야 합니다. 그렇지 않으면 파일이 업로드되지 않습니다.

  • c:\temp 디렉터리를 생성했는지 확인합니다. 및 c:\apache-tomcat5.5.29\webapps\data 미리 잘.

<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "org.apache.commons.fileupload.*" %>
<%@ page import = "org.apache.commons.fileupload.disk.*" %>
<%@ page import = "org.apache.commons.fileupload.servlet.*" %>
<%@ page import = "org.apache.commons.io.output.*" %>

<%
   File file ;
   int maxFileSize = 5000 * 1024;
   int maxMemSize = 5000 * 1024;
   ServletContext context = pageContext.getServletContext();
   String filePath = context.getInitParameter("file-upload");

   // Verify the content type
   String contentType = request.getContentType();

   if ((contentType.indexOf("multipart/form-data") >= 0)) {
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);

      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);

      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try {
         // Parse the request to get file items.
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("<html>");
         out.println("<head>");
         out.println("<title>JSP File upload</title>");
         out.println("</head>");
         out.println("<body>");

         while ( i.hasNext () ) {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) {
               // Get the uploaded file parameters
               String fieldName = fi.getFieldName();
               String fileName = fi.getName();
               boolean isInMemory = fi.isInMemory();
               long sizeInBytes = fi.getSize();

               // Write the file
               if( fileName.lastIndexOf("\\") >= 0 ) {
                  file = new File( filePath +
                  fileName.substring( fileName.lastIndexOf("\\"))) ;
               } else {
                  file = new File( filePath +
                  fileName.substring(fileName.lastIndexOf("\\")+1)) ;
               }
               fi.write( file ) ;
               out.println("Uploaded Filename: " + filePath +
               fileName + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
      } catch(Exception ex) {
         System.out.println(ex);
      }
   } else {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>");
      out.println("</body>");
      out.println("</html>");
   }
%>

이제 위에서 만든 HTML 양식을 사용하여 파일을 업로드해 봅니다. https://localhost:8080/UploadFile.htm을 시도할 때 , 다음 결과를 표시합니다. 이렇게 하면 로컬 컴퓨터에서 파일을 업로드하는 데 도움이 됩니다.

File Upload
Select a file to upload

JSP 스크립트가 제대로 작동하면 파일을 c:\apache-tomcat5.5.29\webapps\data\에 업로드해야 합니다. 디렉토리.