portlet JSR168 上传下载

在portlet  jsR 168中实现上传下载的问题

/**************************************************portlet上传********************************************
public class Fileupload extends GenericPortlet {

 public static final String JSP_FOLDER    = "/download/jsp/html/";    // JSP folder name

 public static final String VIEW_JSP      = "FileuploadView";         // JSP file name to be rendered on the view mode


 public static final String SESSION_BEAN  = "FileuploadSessionBean";  // Bean name for the portlet session

 public static final String FORM_SUBMIT   = "FileuploadFormSubmit";   // Action name for submit form
 public static final String FORM_TEXT     = "FileuploadFormText";     // Parameter name for the text input
    private String tmp_pic_path ="";
    private String filePath ="";
    private String Pic_Path="";
 /**
  * @see javax.portlet.Portlet#init(javax.portlet.PortletConfig)
  */
 public void init(PortletConfig config) throws PortletException{
  super.init(config);
  tmp_pic_path=config.getPortletContext().getRealPath("/WEB-INF/classes");
  //System.out.print("全路径为:"+tmp_pic_path);
 }

 /**
  * Serve up the <code>view</code> mode.
  *
  * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
  */
 public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
  // Set the MIME type for the render response
  response.setContentType(request.getResponseContentType());

  // Check if portlet session exists
  FileuploadSessionBean sessionBean = getSessionBean(request);
  if( sessionBean==null ) {
   response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
   return;
  }
  String[] doc_paths = tmp_pic_path.split("");
  String tmp_path = "";
  for(int i=0;i<doc_paths.length;i++){
   if(i<doc_paths.length-2){
    tmp_path +=doc_paths[i]+"//";
   }   
  }
  filePath = tmp_path;
 
  // Invoke the JSP to render
  PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(sessionBean.getViewJsp());
  rd.include(request,response);
 }

 /**
  * Process an action request.
  *
  * @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
  */
 public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException {
     FileuploadSessionBean sessionBean = getSessionBean(request);
     if( sessionBean==null ) {   
   return;
  }
  ServiceLocator sl=null;
     SingleTableSessionHome  SingleTablehome = null;
     SingleTableSession singleTable =null;
     try {  
   sl = ServiceLocator.getInstance();
   SingleTablehome = (SingleTableSessionHome)sl.getHome("ejb/SingleTableSessionBean",SingleTableSessionHome.class);
   singleTable=SingleTablehome.create(); 
     } catch (Exception e) {  
      e.printStackTrace();
     }
     String fileType ="";
     try{
     // Create a factory for disk-based file items
   DiskFileItemFactory factory = new DiskFileItemFactory();
   PortletFileUpload upload = new PortletFileUpload(factory);  
   //设置factory的大小;
   factory.setSizeThreshold(20*1024);
   factory.setRepository(new File(filePath)); 
   List fileItems = upload.parseRequest(request); //解析请求,返回一个集合.
   upload.setFileSizeMax(20*1024*1024);
   Iterator i = fileItems.iterator(); 
   while(i.hasNext())
   { 
    FileItem fi = (FileItem)i.next();  
    if(fi.isFormField()) //这是用来确定是否为文件属性,
    {   
     String fieldName = fi.getFieldName(); //这里取得表单名 
     if(fieldName.equalsIgnoreCase("fileType")){
      fileType = fi.getString();//获得表单值
      System.out.print("表单的值为:"+fileType); 
     }                     
    }
    else //这里开始处理文件
    {
     String fileName = fi.getName(); // 返回文件名包括客户机路径
     long size = fi.getSize();// 获取上传的文件大小(字节为单位)      
     if ((fileName == null || fileName.equals("")) && size == 0)
     continue;// 跳到while检查条件 
     int end = fileName.length();
  //    返回在此字符串中最右边出现的指定子字符串的索引。
     int begin = fileName.lastIndexOf("//");
              String  name = fileName.substring(begin + 1, end);            
              filePath +=fileType;
              System.out.print("全路径为:"+filePath);
     File savedFile = new File(filePath,name);      
     fi.write(savedFile);       
    }
   }
  }catch(Exception e){  
      e.printStackTrace();
  } 
  sessionBean.setSussesStr("是");
        sessionBean.setViewJsp("uploadjsp.jsp");     
 }

 /**
  * Get SessionBean.
  *
  * @param request PortletRequest
  * @return BasicPortletSessionBean
  */
 private static FileuploadSessionBean getSessionBean(PortletRequest request) {
  PortletSession session = request.getPortletSession();
  if( session == null )
   return null;
  FileuploadSessionBean sessionBean = (FileuploadSessionBean)session.getAttribute(SESSION_BEAN);
  if( sessionBean == null ) {
   sessionBean = new FileuploadSessionBean();
   session.setAttribute(SESSION_BEAN,sessionBean);
  }
  return sessionBean;
 }
}

//就是在doView把文件要上传的路径得到.当然你可以自己决定上传到固定的硬盘下.在这里我是上传到我的工程项目下的一个文件夹下.所以要在doview中的得到要上传的路径.
//**************************************************上传的jsp***************************************
<FORM method="POST" action="<portlet:actionURL/>" name="uploadform" enctype="multipart/form-data">  

<TABLE border="1">
  <TR>
 <TD width="285">文件类型:</TD>
 <TD width="681"> 
   <SELECT name="fileType">
     <OPTION value="systemhelp">系统帮助文档</OPTION>
     <OPTION value="tables">常用表格</OPTION>
     <OPTION value="temp">其他</OPTION>
   </SELECT>
 </TD>
  </TR> 
  <TR>
 <TD width="285">文件上传</TD>
 <TD width="681"><input type="file" name="filePath"></TD>
  </TR>  
</TABLE>  
<p><INPUT name="shangchuan" type="submit"  value="上传"/></p>
</FORM>
/
                                 有了上传下面是下载
大家都知道,在portal中不好来设置content type,无法获得输出流.最好的方式就是在doview()中通过iframe在servlet中实现.
在这里我是用文件的形势实现下载的.

//*********************************************portlet 下载****************************************************************

public void init(PortletConfig config) throws PortletException{
  super.init(config);
  classes_path = config.getPortletContext().getRealPath("/WEB-INF/classes");
 }

 /**
  * Serve up the <code>view</code> mode.
  *
  * @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)
  */
 public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
  // Set the MIME type for the render response
  response.setContentType(request.getResponseContentType());

  // Check if portlet session exists
  FiledownloadSessionBean sessionBean = getSessionBean(request);
  if( sessionBean==null ) {
   response.getWriter().println("<b>NO PORTLET SESSION YET</b>");
   return;
  }
  String[] doc_paths = classes_path.split("");
  String tmp_path = "";
  for(int i=0;i<doc_paths.length;i++){
   if(i<doc_paths.length-2){
    tmp_path +=doc_paths[i]+"//";
   }
   
  }
  filePath = tmp_path;
//  取出是系统帮助文档
  String pathsystem = tmp_path+"systemhelp"; 
  //在这里是获得 pathsystem 文件夹的文件.  
  File sfile=new File(pathsystem);
                //在这里是获得 pathsystem 文件夹下的所有文件.并且放在数组中
  String[] flist=sfile.list();
                //利用sessionBean传到jsp页面上.
  sessionBean.setSystemFiles(flist);
  

  // Invoke the JSP to render
  PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(sessionBean.getViewJSP());
  rd.include(request,response);
 }
/// 在这里同样是在init() 中获得文件的路径.在doview()中获得要下载的文件夹的路径,
/*********************download.jsp********************************

<%@ page import="javax.portlet.*,download.*" %>
<%@ page language="java" contentType="text/html;charset=GB18030"
 pageEncoding="GB18030" session="false"%>
<%@taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
<portlet:defineObjects/>

<%
 FiledownloadSessionBean sessionBean = (FiledownloadSessionBean)renderRequest.getPortletSession().getAttribute(Filedownload.SESSION_BEAN);
 String[] systemfiles = sessionBean.getSystemFiles(); 
%>
 <p><font color="red">系统帮助文档下载</font></p>
<%
  if(systemfiles!=null){
     for(int i=0; i<systemfiles.length;i++){
      %><p>&nbsp;&nbsp;&nbsp;&nbsp;<a href ="<%=renderResponse.encodeURL(renderRequest.getContextPath()) %>/systemhelp/<%=systemfiles[i] %>"><%=systemfiles[i] %></a></p><%    
     }
   
 }
 %>
/
这就基本实现了下载.如果是图片就直接用ie打开.如果是word文档就弹出下载的对话框.

 

 


 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值