p:fileUpload上传的文件保存在哪里,如何更改?

sei*_*cle 12 jsf netbeans file-upload glassfish primefaces

我使用Netbeans开发的Primefaces的简单文件上传.我的测试示例类似于Primefaces手册.
我的问题:文件在我的本地计算机上的哪里上传?我该如何改变它的路径?谢谢!

jsf文件:

<?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:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>Page test</title>
    </h:head>
    <h:body>
        Hello! My first JSF generated page!
        <h:form enctype="multipart/form-data">
            <p:fileUpload value="#{fileBean.file}" mode="simple" />
            <p:commandButton value="Submit" ajax="false"/>
        </h:form>

    </h:body>
</html>
Run Code Online (Sandbox Code Playgroud)

和托管bean:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;


    @ManagedBean

@RequestScoped
public class FileBean {

    private UploadedFile file;

    public FileBean() {
    }

    public UploadedFile getFile() {
        return file;
    }

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

    }
}
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 19

它的默认保存在任何servlet容器的内存或临时文件夹,这取决于文件大小和Apache通用FileUpload配置(见"过滤器配置"的部分<p:fileUpload>章节中PrimeFaces用户指南).

你根本不应该担心这一点.servlet容器和PrimeFaces确切知道它们的作用.您应该在命令按钮的操作方法中实际将上传的文件内容保存到需要的位置.您可以将上传的文件内容作为InputStreamby UploadedFile#getInputStream()或as byte[]by UploadedFile#getContents()获取(byte[]在大文件的情况下获取可能的内存昂贵,你知道,每个文件都byte占用JVM内存的一个字节,因此在大文件的情况下不要这样做) .

例如

<p:commandButton value="Submit" action="#{fileBean.save}" ajax="false"/>
Run Code Online (Sandbox Code Playgroud)

private UploadedFile uploadedFile;

public void save() throws IOException {
    String filename = FilenameUtils.getName(uploadedFile.getFileName());
    InputStream input = uploadedFile.getInputStream();
    OutputStream output = new FileOutputStream(new File("/path/to/uploads", filename));

    try {
        IOUtils.copy(input, output);
    } finally {
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }
}
Run Code Online (Sandbox Code Playgroud)

(FilenameUtils并且IOUtils来自Commons IO,无论如何你已经安装了以便开始<p:fileUpload>工作)

要生成唯一的文件名,您可能会发现File#createTempFile()设施很有帮助.

String filename = FilenameUtils.getName(uploadedFile.getFileName());
String basename = FilenameUtils.getBaseName(filename) + "_";
String extension = "." + FilenameUtils.getExtension(filename);
File file = File.createTempFile(basename, extension, "/path/to/uploads");
FileOutputStream output = new FileOutputStream(file);
// ...
Run Code Online (Sandbox Code Playgroud)