【问题标题】:Uploaded file is set to null in JSF上传的文件在 JSF 中设置为 null
【发布时间】:2017-07-04 00:47:24
【问题描述】:

我在 JSF 中上传文件,它总是null,所以我得到一个NullPointerException

我的backingBean

@ManagedBean
@SessionScoped
public class UploadFile implements Serializable {
    private Part fileUp;

    public String processFileUpload() throws IOException {
        Part uploadedFile = getFileUp();

        final Path destination = Paths.get("c:/temp/" + FilenameUtils.getName(getSubmittedFileName(uploadedFile)));

        InputStream bytes = null;

        if (null != uploadedFile) {

            bytes = uploadedFile.getInputStream();  //Copies bytes to destination.
            Files.copy(bytes, destination);
        }

        return "success";
    }

    public Part getFileUp() {
        return fileUp;
    }

    public void setFileUp(Part fileUp) {
        this.fileUp = fileUp;
    }

我的首页:

<h:form id="fileUpload" enctype="multipart/form-data">

    <h:outputLabel for="fu" value="Name:" />
    <h:inputFile id="fu" value="#{uploadFile.fileUp}">
    </h:inputFile>
    <p>
        <h:messages id="messagesUpload" />
    </p>

    <h:commandButton value="Upload File" action="#{uploadFile.processFileUpload}">
        <f:ajax execute="fileUpload" render="@all" />
    </h:commandButton>
</h:form>

谁能帮我将文件设置为它的值并告诉我为什么它得到空值?

【问题讨论】:

标签: java jsf file-upload


【解决方案1】:

虽然您粘贴的代码似乎不完整,但我怀疑错误可能来自

final Path destination = Paths.get("c:/temp/" + 
FilenameUtils.getName(getSubmittedFileName(uploadedFile)));

所以试试下面的代码。另请注意,您在"c:/temp/" 中以小写字母输入您的c。那是正确的系统路径吗?

public void processUpload() {
    String path = "C:/temp/";
    try (InputStream input = fileUp.getInputStream()) {
        String fileName = fileUp.getSubmittedFileName();
        Files.copy(input, new File(path, fileName).toPath());
    } catch (IOException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e);
    } catch (Exception ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }
}

【讨论】:

    猜你喜欢
    • 2014-03-08
    • 2013-09-12
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多