Servlet Download DoGet Method แก้ปัญหา ไฟล์นอก Web Root

บทความเกี่ยวกับ :Servlet Download DoGet Method แก้ปัญหา ไฟล์นอก Web Root


Servlet Download DoGet Method แก้ปัญหา ไฟล์นอก Web Root

     วันนี้ข้ามฟากมาทาง Web Content นิดหน่ือยนะครับเกี่ยวกับเรื่องการทำ Script Download File
เรื่องแบบนี้ไม่น่าจะยาก ถ้าไฟล์ที่จะทำการ Doanload เก็บอยู่ในห้อง Web content หรือ Web Root
เราก็แค่ทำ Link URL ชี้ไปที่ไฟล์นั้นก็เรียบร้อย
     แต่ถ้าไฟล์นั้นไม่ได้อยู่ในห้อง  Web Root ล่ะจะทำอย่างไร แนวทางง่ายๆ ก็ต้องเขียน โปรแกรมไปอ่านมาน่ะสิแล้วค่อยปล่อยออกไปให้ Download  ผ่าน Servlet ตามตัวอย่างด้านล่าง

  private void doDownload( HttpServletRequest req, HttpServletResponse resp,
                             String filename, String original_filename )
        throws IOException
    {
        File                f        = new File(filename);
        int                 length   = 0;
        ServletOutputStream op       = resp.getOutputStream();
        ServletContext      context  = getServletConfig().getServletContext();
        String              mimetype = null;
        resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
        resp.setContentLength( (int)f.length() );
        resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );

        byte[] bbuf = new byte[1024];
        DataInputStream in = new DataInputStream(new FileInputStream(f));

        while ((in != null) && ((length = in.read(bbuf)) != -1))
        {
            op.write(bbuf,0,length);
        }

        in.close();
        op.flush();
        op.close();
    }

ตามนี้เลยครับ เสร็จแล้วก็ทำการเรียกใช้ผ่าน Method DoGet  ก็เป็นอันประสปผล อิอิ

ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

Oracle date format จัด format date ให้แสดง พศ และ เดือน ภาษาไทยหรือตามภาษาที่เราเลือก

java -Xms , java -Xmx กำหมด memory ให้ JVM เพื่อป้องกันปัญหา Out of Memory

Java this กับ super การใช้งานคำสั่ง this กับ super ใน ภาษา Java