ฉันจะไม่พูดเรื่องไร้สาระมากนักฉันตรงไปที่จุด
ต้องใช้แพ็คเกจสองขวด:
Commons-fileupload.jar
แพ็คเกจคอมมอนส์ io jar (ใช้ Commons-io-2.4.jar ในบทความนี้)
ใช้ servlet เพื่อใช้การอัปโหลดไฟล์
Package Web.servlet; นำเข้า java.io.ioexception; นำเข้า Javax.servlet.servletexception; นำเข้า Javax.servlet.annotation.webservlet; นำเข้า Javax.servlet.http.httpservlet; javax.servlet.http.httpservletResponse; นำเข้า java.io.file; นำเข้า java.util.iterator; นำเข้า java.util.list; นำเข้า org.apache.Commons.FileUpload.fileitem; import org.apache.commons.commons.commons.commons.commons.commons.disc org.apache.commons.fileupload.servlet.servletFileUpload;/*** คลาสการใช้งาน servlet uploadservlet*/@webservlet ("/uploadservlet") คลาสสาธารณะ uploadservlet ขยาย httpservlet // ไดเรกทอรีสำหรับการอัปโหลดไฟล์สตริงส่วนตัว temppath = "d: // temp // buffer //"; // ไฟล์ไดเรกทอรีไฟล์ชั่วคราว temppathfile; โมฆะสาธารณะ dopost (คำขอ httpservletrequest, การตอบสนอง httpservletResponse) พ่น IOException, servletexception {ลอง {// สร้างโรงงานสำหรับไฟล์ที่ใช้ disk ข้อ จำกัด SetSizEthreshold (4096); // ตั้งค่าขนาดบัฟเฟอร์นี่คือ 4KbFactory.SetRepository (TemppathFile); // ตั้งค่าไดเรกทอรีบัฟเฟอร์ // สร้างไฟล์ใหม่อัพโหลด HandlERSERVLETFilePilePileLoad อัปโหลด = ใหม่ servletFileUpload (โรงงาน); // ตั้งค่าขนาดคำขอโดยรวม // ตั้งค่าขนาดไฟล์สูงสุดนี่คือ 4MBLIST <fileItem> items = upload.parserequest (คำขอ); // รับไฟล์ทั้งหมด iterator <fileItem> i = items.iterator (); ในขณะที่ (i.hasnext ()) {fileItem fi = (fileItem) ไฟล์ (fi.getName ()); ไฟล์ savedfile = ไฟล์ใหม่ (uploadpath, fullfile.getName ()); fi.write (savedfile);}} system.out.print ("อัปโหลด successe");} catch (Exception e) {// uploadFile = ไฟล์ใหม่ (uploadPath); ถ้า (! uploadfile.exists ()) {uploadfile.mkdirs ();} ไฟล์ temppathfile = ไฟล์ใหม่ (temppath); ถ้า (! temppathfile.exists ()) JSP
<%@ page language = "java" contentType = "ข้อความ/html; charset = iso-" pageencoding = "utf-"%> <! doctype html สาธารณะ "-// wc // dtd html. transitional // en" "http://www.w.org/tr/html/loose.dtd"><html><head> <meta http-equiv =" content-type "content =" ข้อความ/html; charset = gb "> <url-pattern> ใน <servlet-mapping> ใน web.xml -> <form name = "myform" action = "uploadServlet" method = "post" enctype = "multipart/form-data"> ไฟล์: <br> <input type = "file" name = "myfile"> <br> <br>
สิ่งนี้จะใช้ฟังก์ชั่นการอัปโหลดไฟล์ แน่นอนว่านี่เป็นพื้นฐานที่สุดและศึกษาต่อไป