2012-01-12 60 views
5

我有這個動作類,這個類需要我的反應如何寫入HttpServletResponse響應對象?

更新現在從DownloadStatus類交接應答的照顧,但它看起來是空

public final class DownloadStatus extends ActionSupport implements ServletRequestAware,ServletResponseAware 
{ 
    static Logger logger = Logger.getLogger(DownloadStatus.class); 
    private HttpServletRequest request; 
    private HttpServletResponse response; 
    private File cfile; 
    private String cfileFileName; 

    @Override 
    public String execute() 
    { 

     logger.debug("Inside DownloadStatus.execute method") 

     try { 
      ChainsInvoker invoker = new ChainsInvoker() 
      def executionResponse = invoker.invoke(request, MYChains.download, cfile, cfileFileName) 
      if(executionResponse == null || ErrorHandler.checkIfError(executionResponse)) 
      { 
       return ERROR 
      } 
      response.setContentType("APPLICATION/xml") 

      logger.debug("filename: $cfileFileName") 

      response.addHeader("Content-Disposition", "attachment; filename=\""+cfileFileName+"\"") 
      response.getWriter().print(executionResponse) 
      logger.debug("executionResponse :" + executionResponse) 
      invoker.invoke(MYChains.clean) 
     }catch (Exception exp) { 

      logger.error("Exception while Creating Status ") 
      logger.error(exp.printStackTrace()) 

     } 
     return NONE 
    } 

    @Override 
    public void setServletRequest(HttpServletRequest request) {  this.request = request; } 

    @Override 
    public void setServletResponse(HttpServletResponse response) {  this.response = response; } 

    public File getcfile() {  cfile } 

    public void setcfile(File cfile) {  this.cfile = cfile } 

    public String getcfileFileName() {  cfileFileName } 

    public void setcfileFileName(String cfileFileName){  this.cfileFileName = cfileFileName } 
} 

及以下類寫流進響應

class DownloadStatusResponse implements Command { 

static Logger logger = Logger.getLogger(DownloadStatusResponse.class); 
@Override 
public boolean execute(Context ctx) throws Exception 
{ 
    logger.debug("Inside DownloadStatusResponse.execute() method") 
    OutputStream response = null; 

    if(ctx.get(ContextParams.absFileName) != null && ctx.get(ContextParams.absFileName).toString().trim().length() != 0) 
    { 
HttpServletResponse resp = ctx.get(ContextParams.response) 
/*I am trying to get Response here*/ 

     response=downloadStatusFile(ctx.get(ContextParams.absFileName).toString(),resp) 
    } 

    logger.debug("Response: " + response) 
    ctx.put(ContextParams.response,response); /*ContextParams is a enum of keywords, having response*/ 
    return false; 
} 

private OutputStream downloadStatusFile(String filename,HttpServletResponse resp) 
{ 
    logger.info("Inside downloadStatusFile() method") 

    File fname = new File(filename) 
    if(!fname.exists()) 
    { 
     logger.info("$filename does not exists") 
     return null 
    } 
    else 
    { 

     resp.setContentType("APPLICATION/xml") 
/*Exception: cannot setContentType on null object*/ 

     resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\"") 

     FileInputStream istr = new FileInputStream(fname) 
     OutputStream ostr = resp.getOutputStream() 
     /*I need to use resp.getOutputStream() for ostr*/ 

     int curByte=-1; 

     while((curByte=istr.read()) !=-1) 
      ostr.write(curByte) 

     ostr.flush();   
    }    
    return ostr 
} 

} 

我的問題是如何能夠ostr返回到responseDownloadStatus班?

更新(工作的測試Servlet)

我有下面這樣的servlet這確實讓文件內容爲信息流,並給予它回HttpServletResponse的的工作,但我想在上面的代碼

使用它
public class DownloadServlet extends HttpServlet { 


public void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException { 

    String fileName = req.getParameter("zipFile"); 

    if(fileName == null)  return; 

     File fname = new File(fileName); 
     System.out.println("filename"); 
     if(!fname.exists()) {System.out.println("Does not exists");   return;} 

     FileInputStream istr = null; 
     OutputStream ostr = null; 
     //resp.setContentType("application/x-download"); 
     resp.setContentType("APPLICATION/ZIP"); 
     resp.addHeader("Content-Disposition", "attachment; filename=\""+fname.getName()+"\""); 
     System.out.println(fname.getName()); 
     try { 
      istr = new FileInputStream(fname); 
      ostr = resp.getOutputStream(); 
      int curByte=-1; 

       while((curByte=istr.read()) !=-1) 
        ostr.write(curByte); 

      ostr.flush(); 
     } catch(Exception ex){ 
      ex.printStackTrace(System.out); 
     } finally{ 
      try { 
      if(istr!=null) istr.close(); 
      if(ostr!=null) ostr.close(); 
      } catch(Exception ex){ 

       ex.printStackTrace(); 
      System.out.println(ex.getMessage()); 
      } 
     } 
     try { 
      resp.flushBuffer(); 
     } catch(Exception ex){ 
      ex.printStackTrace(); 
      System.out.println(ex.getMessage()); 
     } 
    } 
} 
+0

爲什麼你流和Servlet API玩弄直接而它可以用流結果 – 2012-01-12 07:19:23

+0

'完成ostr'是'OutputStream',但'response'是'HttpServletResponse'。你是說你的意思是* ostr返回響應*? – 2012-01-12 07:32:31

+0

@Umesh:我不熟悉下載的東西!所以我來工作了@首先我跟着它,如果有更好的方式幫助我:)謝謝 – Ricky 2012-01-12 09:17:22

回答

4

據我瞭解,您所需要的只是如何使用Struts2下載文件。

你需要這樣的東西,這是你的struts.xml文件

<action name="downloadfile" class="DownloadAction"> 
      <result name="success" type="stream"> 
       <param name="contentType">application/pdf</param> 
       <param name="inputName">inputStream</param> 
       <param name="contentDisposition">attachment;filename="document.pdf"</param> 
       <param name="bufferSize">1024</param> 
      </result> 
     </action> 

代碼:

public class DownloadAction extends ActionSupport { 

    private InputStream inputStream; 

    public InputStream getInputStream() { 
    return inputStream; 
    } 

    public void setInputStream(InputStream inputStream) { 
    this.inputStream = inputStream; 
    } 

    public String execute() throws FileNotFoundException { 
    String filePath = ServletActionContext.getServletContext().getRealPath("/uploads"); 
    File f = new File(filePath + "/nn.pdf"); 
    System.out.println(f.exists()); 
    inputStream = new FileInputStream(f); 
    return SUCCESS; 
    } 
} 
+0

XCoder:感謝它幫助我解決了我的問題 – Ricky 2012-01-17 05:45:13

+0

爲什麼鏈接到外部資源通常是不被接受的。鏈接現在已經死了,這個答案沒什麼意義。 – thecoshman 2013-06-25 07:48:27

+1

@thecoshman我已經添加了行動代碼,希望現在有意義。對不起,斷開的鏈接,我已經刪除它。 – 2013-06-25 14:31:52