rss· 投稿· 设为首页· 加入收藏· 繁體版

jsf文件上传

a.:
实现jsf应用的文件上传功能,可以使用MyFaces文件上传组件
依赖的库有 commons-io.jar,myfaces-api.jar,myfaces-impl.jar,tomahawk.jar
web.xml:
 <filter>
   <filter-name>MyfacesExtensionsFilter</filter-name>
   <filter-class>
    org.apache.myfaces.webapp.filter.ExtensionsFilter
   </filter-class>
   <init-param>
    <param-name>uploadMaxFileSize</param-name>
    <param-value>10m</param-value>
   </init-param>
   <init-param>
    <param-name>uploadThresholdSize</param-name>
    <param-value>50k</param-value>
   </init-param>
   <init-param>
    <param-name>uploadRepositoryPath</param-name>
    <param-value>../</param-value>
   </init-param>
 </filter>

 <filter-mapping>
  <filter-name>MyfacesExtensionsFilter</filter-name>
  <servlet-name>Faces Servlet</servlet-name>
 </filter-mapping>
 <filter-mapping>
  <filter-name>MyfacesExtensionsFilter</filter-name>
  <url-pattern>/faces/myFacesExtensionResource/*</url-pattern>
 </filter-mapping>

 ////////////////////////////////
 其他的jsf 和 myFaces 配置就不写在这里了

 //////////////////////////////////

entity:student
public class Student{
 public Student(){
 }

 private byte[] stuFileData;
 private String stuFileName;

 public void setStuFuleData(byte[] stuFileData){
  this.stuFileData = stuFileData;
 }
 public byte[] getStuFileData(){
  return this.stuFileData;
 }
 public void setStuFileName(String stuFileName){
  this.stuFileName = stuFileName;
 }
 public String getStuFileName(){
  return this.stuFileName;
 }
 }
 受管bean:StudentAction

 import org.apache.myfaces.custom.fileupload.UploadedFile;

 public StudentAction{
 private UploadedFile _upFile;

 public String addStudent(){
   // 获得文件的全名,含路径
  String fileName = _upFile.getName();
  if (!fileName.equals("")) {
   File temp = new File(fileName);
   // 获得文件名
   fileName = temp.getName();
  }
  byte[] buffer = new byte[new Long(_upFile.getSize()).intValue()];
  try {
   buffer = _upFile.getBytes();
  } catch (IOException e) {
   e.printStackTrace();
  }

  Student student = new Student();
  student.setStuDataName(fileName);
  student.setStuDataFileData(buffer);

  //studentDAO.save(student);
  return null;
 }

 public String down(){
  try {
   //先检索student
   Student student = stdentDAO.getStudent();

   System.err.println("...................in...............");
   FacesContext ctx = FacesContext.getCurrentInstance();
   HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
   String contentType = "application/x-msdownload;charset=utf-8";
   response.setContentType(contentType);
   response.setHeader("Content-disposition", "attachment; filename=\"" +student.getStuFileName+"\"");
   ServletOutputStream out = response.getOutputStream();  
   if(null!=crFile)
   out.write(crFile);
   out.flush();
   ctx.responseComplete();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return null;
 }

 public UploadedFile get_upFile() {
  return _upFile;
 }

 public void set_upFile(UploadedFile file) {
  _upFile = file;
 }
 }

jsp:
首先引入标签
<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%>
 <h:form id="from" enctype="multipart/form-data">
 <t:inputFileUpload id="fileupload" value="#{StudentAction._upFile}"/>
 <h:commandButton action="StudentAction.addStudent" value="保存"/>
 <h:commandButton action="StudentAction.down" value="下载附件"/>
</h:form>

以上程序未经调试,运行时可能会出现错误,不过用 myFaces 实现 jsf 的文件上传功能
需要注意的要点和关键性代码都已将完成了。
b.seam 的文件上传
  seam应用的文件上传也可以使用 myFaces,使用方法和上面相同。
  不过seam自身也提供了附件上传的组件功能,而且实现起来更简单:
  xhtml文件:
  首先引入标签
  xmlns:s="http://jboss.com/products/seam/taglib"
  <h:form id="from" enctype="multipart/form-data">
   <s:fileUpload id="myFile" fileName="#{student.stuFileName}" data="#{student.stuFileData}"/>
   <a4j:commandButton value="保存" action="#{StudentAction.addStuent}"/>
   <a4j:commandButton value="下载附件" action="#{StudentAction.down}"/>
  </h:form>

 受管bean:StudentAction

 import org.apache.myfaces.custom.fileupload.UploadedFile;

 public StudentAction{
 private Student student;
 @In(request=false,create=true)
 @Out(request=false)
 public String addStudent(){
  //studentDAO.save(student);
  return null;
 }

 public String down(){
  try {
   //先检索student
   Student student = stdentDAO.getStudent();
   FacesContext ctx = FacesContext.getCurrentInstance();
   HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
   String contentType = "application/x-msdownload;charset=utf-8";
   response.setContentType(contentType);
   response.setHeader("Content-disposition", "attachment; filename=\""   +student.getStuFileName+"\"");
   ServletOutputStream out = response.getOutputStream();  
   if(null!=crFile)
   out.write(crFile);
   out.flush();
   ctx.responseComplete();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
  return null;
 }
 }

entity:student
@Name("student")
public class Student{
 public Student(){
 }

 private byte[] stuFileData;
 private String stuFileName;
 
 public void setStuFuleData(byte[] stuFileData){
  this.stuFileData = stuFileData;
 }

 @Column(name="StuFileData",length=2147483647)
 @Basic(fetch=FetchType.LAZY)
 @Lob
 public byte[] getStuFileData(){
  return this.stuFileData;
 }
 public void setStuFileName(String stuFileName){
  this.stuFileName = stuFileName;
 }
 @Column(name = "StuFileName", length = 100)
 @Length(max = 100)
 public String getStuFileName(){
  return this.stuFileName;
 }
 }

特别注意 jsp form 的提交方式
<h:form id="from" enctype="multipart/form-data">
否则fileData不能传递到受管 bean

*********************************   最近项目需要用jsf1.2实现文件上传功能,我没有采用myfaces,而是用Apache MyFaces Trinidad 这个实现的文件上传,实现方法和myfaces是一样的。页面采用的是.xhtml。

    Apache MyFaces Trinidad是一个基于部分Oracle's ADF Faces构建的JSF1.2组件库。我们要先下在它的jar包,然后导入到我们工程里面。http://myfaces.apache.org/trinidad/index.html这个链接里有文档和包的下载。

    下面来看看代码,首先要配置web.xml文件,配置文件里的UPLOAD_MAX_MEMORY设置成500k说明只要是小于500k的文件都会存放在memory里面,UPLOAD_MAX_DISK_SPACE设置成5000k说明上传文件最大为5000k,并且大小在500k和5000k之间的文件才会存放在磁盘默认路径里面,UPLOAD_TEMP_DIR用来设置存放文件的路径

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <context-param>
    <!-- Maximum memory per request (in bytes) -->
    <param-name>org.apache.myfaces.trinidad.UPLOAD_MAX_MEMORY</param-name>
    <!-- Use 500K -->
    <param-value>512000</param-value>
  </context-param>
  <context-param>
    <!-- Maximum disk space per request (in bytes) -->
    <param-name>org.apache.myfaces.trinidad.UPLOAD_MAX_DISK_SPACE</param-name>
    <!-- Use 5,000K -->
    <param-value>5120000</param-value>
  </context-param>
  <context-param>
    <!-- directory to store temporary files -->
    <param-name>org.apache.myfaces.trinidad.UPLOAD_TEMP_DIR</param-name>
    <!-- Use a TrinidadUploads subdirectory of /tmp -->
    <param-value>/tmp/TrinidadUploads/</param-value>
  </context-param>

  <!-- This filter is always required;  one of its functions is
          file upload. -->
  <filter>
    <filter-name>trinidad</filter-name>
    <filter-class>org.apache.myfaces.trinidad.webapp.TrinidadFilter</filter-class>
  </filter>

</web-app>

然后是faces-config.xml的配置信息

<?xml version='1.0' encoding='UTF-8'?>

<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
    version="1.2">

    <!--  upload files by lw -->
    <navigation-rule>
        <from-view-id>/upload/upload.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>uploadedfile</from-outcome>
            <to-view-id>/upload/uploadlist.xhtml</to-view-id>
        </navigation-case>
    </navigation-rule>
    <managed-bean>
        <managed-bean-name>upLoadBean</managed-bean-name>
        <managed-bean-class>
            com.lw.bean.UpLoadBean
        </managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>

    </managed-bean>
</faces-config>
UpLoadBean类

package com.lw.bean;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.myfaces.trinidad.model.UploadedFile;

public class UpLoadBean ...{

    private UploadedFile file;

    public UploadedFile getFile() ...{
        return file;
    }

    public void setFile(UploadedFile file) ...{
        this.file = file;
    }

    public String uploadedfile() ...{

        try ...{
            FacesContext context = FacesContext.getCurrentInstance();
            //在控制台输出上传文件的文件名,和文件大小
            FacesMessage message = new FacesMessage(
                    "Successfully uploaded file" + file.getFilename() + "("
                            + file.getLength() + "bytes)");
            context.addMessage(null, message);

            InputStream stream;
            stream = new BufferedInputStream(file.getInputStream());
            byte[] bytes = new byte[1024 * 1024];//设定文件大小
            @SuppressWarnings("unused")
            int count;
            count = stream.read(bytes);
            stream.close();//关闭流
            return "uploadedfile";
        } catch (IOException e) ...{
            e.printStackTrace();
            return null;
        }
    }

上传页面upload.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:u="http://java.sun.com/blueprints/ui"
    xmlns:c="http://java.sun.com/jsp/jstl/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:a4j="https://ajax4jsf.dev.java.net/ajax"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:tr="http://myfaces.apache.org/trinidad" xml:lang="en" lang="en">
    <head>
        <title>My Facelets Page</title>
        <meta http-equiv="keywords" content="enter,your,keywords,here" />
        <meta http-equiv="description"
            content="A short description of this page." />
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

        <!--<link rel="stylesheet" type="text/css" href="styles.css">-->

        <script>
</script>
    </head>
    <body>
        <f:view>

            <tr:form usesUpload="true">
                <tr:inputFile label="上传:" value="#{upLoadBean.file}" />
                <tr:commandButton text="开始" action="#{upLoadBean.uploadedfile}" />
            </tr:form>

        </f:view>

    </body>
</html>

显示上传文件的文件名和文件大小的页面uploadlist.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core" xml:lang="en" lang="en">
    <head>
        <title>My Facelets Page</title>
        <meta http-equiv="keywords" content="enter,your,keywords,here" />
        <meta http-equiv="description"
            content="A short description of this page." />
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

        <!--<link rel="stylesheet" type="text/css" href="styles.css">-->
    </head>
    <body>
        <f:view>

            <h:panelGrid border="0" columns="2" style="width: 411px">
                <h:outputText value="文件名:" />
                <h:outputText value="#{upLoadBean.file.filename}" />
                <h:outputText value="文件大小:" />
                <h:outputText value="#{upLoadBean.file.length}" />
            </h:panelGrid>

        </f:view>
    </body>
</html>

现在功能已经实现了,不过这个程序上传的文件成功后,会把文件变成tmp文件,不过我需要的功能已经实现了,因为我上传的是excel和work文件,然后用POI解析tmp文件,把它存入数据库就可以了。

********************************

顶一下
(0)
踩一下
(0)