通过接口下载服务上pdf文件

 

需要配置web.xml来通过跳过登陆验证

 

package com.whir.rd.service;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.whir.common.path.SystemPath;
import com.whir.component.config.ConfigXMLReader;

public class DownSWLoadServelt extends HttpServlet {
    private static Logger logger = Logger.getLogger(DownSWLoadServelt.class
            .getName());
    private static final ConfigXMLReader reader = new ConfigXMLReader();

    /**
     * Constructor of the object.
     */
    public DownSWLoadServelt() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
          
            String downloadFile;
           
            String FileName = request.getParameter("FileName");

 
            if ((FileName.startsWith("/")) || (FileName.startsWith("./")) || (FileName.startsWith("../"))) {
              return;
            }
            if(FileName==""||FileName.length()<=0){
                return;
                
            }
            String ggpath=SystemPath.getRootFilePath() + File.separator + "upload" + File.separator;
            String yearmonth=FileName.substring(0, 6);
            String newPdfPaths = ggpath+"tempfile/temppdf/" + yearmonth + "/";
            String srcFile = newPdfPaths +FileName;
            System.out.println("开始复制文件srcFile"+srcFile);
        
        

            String mimeType ="application/pdf";
*/            
          /*  OutputStream out = null;
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "99999999.pdf");
            writeBytes(srcFile, response.getOutputStream());
           
              File file = new File(srcFile);
              if (file.exists()) {
                //你的文件所存放的地址 我这边放在e盘下
                    DataOutputStream temps = new DataOutputStream(response.getOutputStream());
                    DataInputStream in = new DataInputStream(new FileInputStream(srcFile));
                    byte[] b = new byte[2048];
                    while ((in.read(b)) != -1) {
                        temps.write(b);
                        temps.flush();
                    }
                    in.close();
                    temps.close();
                } else {
                   System.out.println("文件不存在");
                }
*/

              //获取服务器文件
            File file = new File(srcFile);

            InputStream ins = new FileInputStream(file);
            /* 设置文件ContentType类型,这样设置,会自动判断下载文件类型 */
            response.setContentType("multipart/form-data");
            /* 设置文件头:最后一个参数是设置下载文件名 */
            response.setHeader("Content-Disposition", "attachment;filename="+file.getName());
            try{
                OutputStream os = response.getOutputStream();
                byte[] b = new byte[1024];
                int len;
                while((len = ins.read(b)) > 0){
                    os.write(b,0,len);
                }
                os.flush();
                os.close();
                ins.close();
            }catch (IOException ioe){
               ioe.printStackTrace();
            }
              
            /*  response.reset();
              response.setContentType(mimeType);
              response.setHeader("Content-Disposition", "attachment; filename=" + FileName);
              response.setContentLength((int)file.length());
              in = new BufferedInputStream(new FileInputStream(file));
              out = new BufferedOutputStream(response.getOutputStream());
              byte[] buf = new byte[8192];
              int n = -1;
              if ("1".equals(isEncrypt))
                while (-1 != (n = in.read(buf, 0, buf.length))) {
                  for (int i0 = 0; i0 < n; ++i0) {
                    buf[i0] = (byte)(buf[i0] + 1);
                  }
                  out.write(buf, 0, n);
                }
              else {
                do
                  out.write(buf, 0, n);
                while (-1 != (n = in.read(buf, 0, buf.length)));
              }

              out.flush();
            }
            catch (IOException e) {
              e.printStackTrace();
            } catch (Exception e) {
              throw new ServletException("Download failed", e);
            } finally {
              try {
                if (in != null)
                  in.close();
              }
              catch (Exception localException7) {
              }
              try {
                if (out != null)
                  out.close();
              } catch (Exception localException8)
              {
              } */
           
    }

     /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }
    
    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to
     * post.
     *
     * @param request
     *            the request send by the client to the server
     * @param response
     *            the response send by the server to the client
     * @throws ServletException
     *             if an error occurred
     * @throws IOException
     *             if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException
     *             if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

    public void printResult(HttpServletResponse response, String content) {
        printResult(response, content, "null");
    }

    public void printResult(HttpServletResponse response, String content,
            String dataJson) {
        
        String result = dataJson;
        //System.out.println("result:" + result);
        try {
            PrintWriter pw = response.getWriter();
            pw.print(result);
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out
                    .println("[BaseActionSupport][method=printResult]异常:" + e);
        }
    }

    
}

posted @ 2021-02-18 13:45  向上丶  阅读(427)  评论(0编辑  收藏  举报