Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม

วิธีอัปโหลดไฟล์ด้วย JSP

JSP รองรับการอัปโหลดไฟล์ผ่าน HTML form แบบ multipart/form-data

1. HTML Upload Form

<html>
<head><title>ฟอร์มอัปโหลดไฟล์</title></head>
<body>
    <h3>อัปโหลดไฟล์:</h3>
    เลือกไฟล์: <br/>
    <form action="UploadFile.jsp" method="post" enctype="multipart/form-data">
        <input type="file" name="file" size="50" /><br/>
        <input type="submit" value="Upload File" />
    </form>
</body>
</html>

เงื่อนไข form:

  • method="POST"
  • enctype="multipart/form-data"
  • input type="file"

2. กำหนดที่เก็บไฟล์ใน web.xml

<context-param>
    <param-name>file-upload</param-name>
    <param-value>C:/apache-tomcat/webapps/data/</param-value>
</context-param>

3. UploadFile.jsp (ใช้ Apache Commons FileUpload)

<%@ page import="java.io.*,java.util.*,javax.servlet.*,javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.*,org.apache.commons.io.output.*" %>
<%
    int maxFileSize = 5 * 1024 * 1024;  // 5MB
    int maxMemSize = 5 * 1024 * 1024;
    
    String filePath = pageContext.getServletContext().getInitParameter("file-upload");
    String contentType = request.getContentType();
    
    if (contentType != null && contentType.contains("multipart/form-data")) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(maxMemSize);
        factory.setRepository(new File("C:\\temp"));
        
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxFileSize);
        
        try {
            List<FileItem> items = upload.parseRequest(request);
            out.println("<h3>อัปโหลดสำเร็จ</h3>");
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();  // ป้องกัน path traversal
                    File file = new File(filePath, fileName);
                    item.write(file);
                    out.println("ไฟล์: " + fileName + " (" + item.getSize() + " bytes)<br/>");
                }
            }
        } catch (Exception e) {
            out.println("Error: " + e.getMessage());
        }
    } else {
        out.println("กรุณาเลือกไฟล์");
    }
%>

Dependencies (WEB-INF/lib)

  • commons-fileupload-x.x.jar
  • commons-io-x.x.jar

Servlet 3.0+ (Tomcat 7+) - ไม่ต้องใช้ Library

<%@ page import="javax.servlet.*,javax.servlet.http.*,java.io.*" %>
<%
    Part filePart = request.getPart("file");
    String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
    filePart.write(pageContext.getServletContext().getInitParameter("file-upload") + File.separator + fileName);
%>

ข้อควรระวังด้านความปลอดภัย

  • ตรวจสอบ file type (MIME type, extension)
  • จำกัดขนาดไฟล์
  • Sanitize file name (ป้องกัน path traversal)
  • เก็บไฟล์นอก web root (ไม่เข้าถึงได้โดยตรงผ่าน URL)
  • Scan virus/malware ถ้าจำเป็น