JSF 2.0 File upload

2019-01-01 00:44发布

I am looking around a few blogs, to try to find how to upload files using JSF 2.0 But all the solutions kind of confuse me. I would like to know what do I exactly need to be able to successfully upload a file(MP3, PDF, video... what ever type) and store it in a database as a @Lob. This is what I have done so far:

  • I created an entity that has an attribute of type byte[] and it is also annotated with a @Lob annotation.

  • I created an EJB that will introduce the entity with with a method that has a byte[] as a parameter and inserts it into the database using the EntityManager class( persist method).

  • I created a JSF page with an input tag of type "file" and a submit button

  • I prepared a managed bean to interchange information about the file with the JSF page.

Now I am stuck, and I have lots of doubts:

  • What should I do to pass the file from the JSF to the managed bean and then transform it to a byte[](To be able to handle it over to the EJB)?

  • How can a servlet help me?

  • Do I need a servlet to do this?

  • Also I found that in some blog it mentions something about servlets 3.0, but I don't know if my working environment is using it, how can if I am using servlets 3.0 (I am using JEE6)?

I never did file upload before and also I am not very familiar with servlets. I am confused, someone could give me some starting tips, please?

8条回答
与风俱净
2楼-- · 2019-01-01 01:04

The easiest way is probably to use the inputFileUpload tag that you can find in MyFaces:

http://myfaces.apache.org/

查看更多
怪性笑人.
3楼-- · 2019-01-01 01:08

BalusC's blog post: Uploading files with JSF 2.0 and Servlet 3.0 is what saved me, because I had problems running RichFaces 4 fileUpload tag with Spring WebFlow.

It's worth to modify BalusC's code to use Spring's MultipartResolver - you don't need his MultipartMap from another blog post.

I achieved it by modifying a decode method in FileRenderer like this:

    UploadedFile ret = null;

    Object req = context.getExternalContext().getRequest();
    if (req instanceof MultipartHttpServletRequest) {
      MultipartFile file = ((MultipartHttpServletRequest)req).getFile(clientId);

      File temp = null;
      try {
        temp = File.createTempFile("_UPLOAD_", null);
        file.transferTo(temp);

        String name = new File(file.getOriginalFilename()).getName();
        ret = new UploadedFile(temp, name);

      } catch (IOException e) {
        throw new RuntimeException("Could not create temp file.", e);
      }
    } else {
      throw new IllegalStateException("Request is not multipart. Use spring's multipart resolver.");
    }
    // If no file is specified, set empty String to trigger validators.
    ((UIInput) component).setSubmittedValue( ret == null ? EMPTY_STRING : ret);

A UploadedFile is a simple serializable POJO used to return results to backing bean.

查看更多
冷夜・残月
4楼-- · 2019-01-01 01:10

For completeness, I just want to provide a fully functional self contained example of how this is done with JSF 2.2, either with non-Ajax and Ajax requests. Keep in mind JSF 2.2 uses different namespaces and you need to be working with a Servlet 3.0 container (as Tomcat 7.0.x, JBoss AS 6.x and 7.x and GlassFish 3.x are).

fileUpload.xhtml

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head />
<h:body>
    <h:form enctype="multipart/form-data">
        <h:inputFile value="#{uploadBean.file}" />
        <h:commandButton value="Post Upload" action="#{uploadBean.upload}" />
    </h:form>
    <h:form enctype="multipart/form-data">
        <h:inputFile value="#{uploadBean.file}" />
        <h:commandButton value="Ajax Upload">
            <f:ajax listener="#{uploadBean.upload}" execute="@form"
                render="countOutput" />
        </h:commandButton>
    <!-- Counts the uploaded items -->
    <h:outputText id="countOutput"
        value="Files uploaded #{uploadBean.filesUploaded}" />
    </h:form>
</h:body>
</html>

UploadBean.java:

@ManagedBean
@ViewScoped
public class UploadBean {

    private int filesUploaded = 0;

    //javax.servlet.http.Part (Servlet 3.0 API)
    private Part file;
    private String fileContent;

    /**
     * Just prints out file content
     */
    public void upload() {
        try {
            fileContent = new Scanner(file.getInputStream())
                    .useDelimiter("\\A").next();
            System.out.println(fileContent + " uploaded");
            filesUploaded++;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int getFilesUploaded() {
        return filesUploaded;
    }

    public Part getFile() {
        return file;
    }

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

See also:

查看更多
妖精总统
5楼-- · 2019-01-01 01:10

In JSF 2.2 you can easily upload file using tag without using commons-io or filter. This tag support both normal and ajax process.

Normal:

    <h:inputFile id="file"  value="#{fileUploadBean.uploadedFile}"/> 
    <h:commandButton id="button" action="#{fileUploadBean.sumbit()}" value="Upload"/>

Ajax:

    <h:inputFile id="file" value="#{fileUploadBean.uploadedFile}"/> 
    <h:commandButton id="button" value="submit">
      <f:ajax execute="@all" render="@all" onevent="statusUpdate"/>
    </h:commandButton>

Design your managed bean as follows:

  @Named
  @RequestScoped
  public class FileUploadBean {

   private Part uploadedFile;

  }
查看更多
高级女魔头
6楼-- · 2019-01-01 01:18

I would recommend using a companent library like Tomahawk's <t:inputFileUpload> or PrimeFaces <p:fileUpload>.

BalusC also has a nice blog post about Uploading files with JSF 2.0 and Servlet 3.0.

查看更多
深知你不懂我心
7楼-- · 2019-01-01 01:21

IceFaces2.0 has one, http://wiki.icefaces.org/display/ICE/FileEntry Haven't tried implementing it yet, but the download has sample apps and it works under Tomcat 6 (servlet 2.5, so not JEE6)

查看更多
登录 后发表回答