บทความนี้แชร์รหัสเฉพาะสำหรับการดาวน์โหลดไฟล์ servlet สำหรับการอ้างอิงของคุณ เนื้อหาเฉพาะมีดังนี้
ไม่ปลอดภัยที่จะเปิดเผยไดเรกทอรีไฟล์โดยตรงไปยังผู้ใช้ ดังนั้นคุณต้องใช้ Servlets และด้วยวิธีนี้ไฟล์จะถูกเก็บไว้อย่างมากมาย พวกเขาสามารถเรียกคืนได้จากระบบไฟล์ที่สร้างขึ้นโดยการคำนวณในฐานข้อมูลหรือดึงมาจากสถานที่แปลก ๆ อื่น ๆ
Public Class DownloadServlet ขยาย httpservlet {สตริงส่วนตัว contentType = "แอปพลิเคชัน/x-msdownload"; สตริงส่วนตัว ENC = "UTF-8"; สตริงส่วนตัว fileroot = ""; / ** * เริ่มต้น ContentType, ENC, fileroot */ public void init (servletConfig config) พ่น servletexception {string tempstr = config.getInitParameter ("contentType"); if (tempstr! = null &&! tempstr.equals ("")) {contentType = tempStr; } tempStr = config.getInitParameter ("Enc"); if (tempstr! = null &&! tempstr.equals ("")) {enc = tempstr; } tempStr = config.getInitParameter ("fileroot"); if (tempstr! = null &&! tempstr.equals ("")) {fileroot = tempstr; }} void doget ที่ได้รับการป้องกัน (คำขอ httpservletRequest, การตอบสนอง httpservletResponse) พ่น servletexception, ioexception {string filepath = request.getParameter ("filepath"); String fullFilePath = fileroot + filePath; /*อ่านไฟล์*/ ไฟล์ = ไฟล์ใหม่ (fullFilePath); /*หากไฟล์มีอยู่*/ if (file.exists ()) {string filename = urlencoder.encode (file.getName (), ENC); Response.reset (); Response.SetContentType (ContentType); Response.addheader ("เนื้อหา-การจัดสรร", "เอกสารแนบ; filename =/" " + filename +"/""); int filelength = (int) file.length (); Response.SetContentLength (Filelength); /*หากความยาวของไฟล์มากกว่า 0*/ if (filelength! = 0) {/*สร้างสตรีมอินพุต*/ inputstream instream = ใหม่ fileInputStream (ไฟล์); ไบต์ [] buf = ไบต์ใหม่ [4096]; /*สร้างสตรีมเอาต์พุต*/ servletoutputstream servletos = response.getOutputStream (); int readLength; ในขณะที่ (((readLength = stream.read (buf))! = -1)) {servletos.write (buf, 0, readLength); } stream.close (); servletos.flush (); servletos.close (); - web.xml
<servlet> <servlet-name> downloadservlet-name> <servlet-class> org.mstar.servlet.downloadservletservlet-class> <init-Param> <param-Name> filerootparam-name> <param-value> <param-value> แอปพลิเคชัน/x-msdownloadparam-value> init-param> <init-param> <param-name> encparam-name> <param-value> utf-8param-value >>> init-param> servlet> <servlet-mapping>
ข้างต้นเป็นเนื้อหาทั้งหมดของบทความนี้ ฉันหวังว่ามันจะเป็นประโยชน์ต่อการเรียนรู้ของทุกคนและฉันหวังว่าทุกคนจะสนับสนุน wulin.com มากขึ้น