หน้าเว็บ

วันอาทิตย์ที่ 10 มิถุนายน พ.ศ. 2555

Servlet download file (java)




package com.blogspot.na5cent;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "DownloadFile", urlPatterns = {"/DownloadFile"})
public class DownloadFile extends HttpServlet {

    private static final int BYTES_DOWNLOAD = 1024;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //set header
        response.setContentType("image/jpg");
        response.setHeader("Content-Disposition", "attachment;filename=Download_Koala.jpg");
        
        File download = new File("c:\\temp\\", "Koala.jpg");
        
        InputStream inputStream = null;
        OutputStream outputStream = null;
        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        try {
            inputStream = new FileInputStream(download);
            outputStream = response.getOutputStream();

            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        }

        /* if you use google common io

           import com.google.common.io.ByteStreams;
           import com.google.common.io.Closeables;

        try {
            inputStream = new FileInputStream(download);
            ByteStreams.copy(inputStream, response.getOutputStream());
        } finally {
            inputStream.close();
            Closeables.close(inputStream, false);
        }
        */
    }
}

ไม่มีความคิดเห็น:

แสดงความคิดเห็น