bbs/insert2.jsp > JSP

본문 바로가기

사이트 내 전체검색

뒤로가기 JSP

bbs/insert2.jsp

페이지 정보

작성자 관리자 작성일 24-10-22 12:05 조회 90 댓글 0

본문

xml

코드 복사

<servlet>

    <servlet-name>FileUploadServlet</servlet-name>

    <servlet-class>com.example.FileUploadServlet</servlet-class>

</servlet>

<servlet-mapping>

    <servlet-name>FileUploadServlet</servlet-name>

    <url-pattern>/upload</url-pattern>

</servlet-mapping>



java

코드 복사

import jakarta.servlet.annotation.MultipartConfig;

import jakarta.servlet.http.HttpServlet;

import jakarta.servlet.http.HttpServletRequest;

import jakarta.servlet.http.HttpServletResponse;

import jakarta.servlet.http.Part;


import java.io.File;

import java.io.IOException;


@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB

                 maxFileSize = 1024 * 1024 * 10,      // 10MB

                 maxRequestSize = 1024 * 1024 * 50)   // 50MB

public class FileUploadServlet extends HttpServlet {

    private static final String UPLOAD_DIR = "upload";


    protected void doPost(HttpServletRequest request, HttpServletResponse response)

            throws IOException {

        String applicationPath = request.getServletContext().getRealPath("");

        String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;

        

        File uploadDir = new File(uploadFilePath);

        if (!uploadDir.exists()) {

            uploadDir.mkdirs();

        }


        for (Part part : request.getParts()) {

            String fileName = extractFileName(part);

            String filePath = uploadFilePath + File.separator + fileName;

            part.write(filePath);

        }

        

        response.getWriter().print("File uploaded successfully.");

    }


    private String extractFileName(Part part) {

        String contentDisposition = part.getHeader("content-disposition");

        String[] items = contentDisposition.split(";");

        for (String s : items) {

            if (s.trim().startsWith("filename")) {

                return s.substring(s.indexOf("=") + 2, s.length() - 1);

            }

        }

        return "";

    }

}





추천0

댓글목록 0

등록된 댓글이 없습니다.


Copyright © dancePKT. All rights reserved.
PC 버전으로 보기