gpt4 book ai didi

tomcat - 如何使用 primefaces 在 apache tomcat 中上传文件?

转载 作者:行者123 更新时间:2023-11-28 22:55:51 24 4
gpt4 key购买 nike

我想知道当我们使用 primefaces 和使用 apache tomcat 服务器上传文件时会发生什么。据我所知,在将其上传到系统之前,tomcat 会暂时存储在某个地方。如果上传成功,我们可以在那个临时文件夹中看到吗?如果文件较大,它会抛出这样的错误。

SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/maintenance] threw                 exception
java.io.IOException: Processing of multipart/form-data request failed. No space left on device

有什么帮助吗?提前致谢。

P.S 我正在使用 Unix

最佳答案

我使用 apache tomcat,这对我来说很好用:

表单必须是 enctype="multipart/form-data 并将它们添加到 web.xml

<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value>
</context-param>

<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>

在 xhtml 文件中:

<h:form enctype="multipart/form-data" id="upload">
<p:fileUpload id="fileUpload" fileUploadListener="#{uploadParcelBean.handleFileUpload}" mode="advanced"
allowTypes="/(\.|\/)(gif|jpe?g|png|bmp|pdf|doc|docx|xls|xlsx|txt)$/"
description="Select File"
label="Select File" uploadLabel="Upload" cancelLabel="Cancel"
validatorMessage="Invalid Format."
dragDropSupport="true"
multiple="true"
update="growl fileList"
disabled="false"/>
</h:form>

在bean端,你可以处理上传的文件:

public void handleFileUpload(FileUploadEvent event) {    
try {
copyFile(event.getFile().getFileName(), event.getFile().getInputstream());
//other logics
}
catch(IOException e){
e.printStackTrace();
}

复制方法类似于:

public void copyFile(String fileName, InputStream in) {

String destination="C:\\uploads\\";
try {

// write the inputStream to a FileOutputStream

File theDir = new File(destination);
if(!theDir.exists())
{
try {
theDir.mkdir();

} catch (Exception e) {
e.printStackTrace();
}

}


OutputStream out = new FileOutputStream(new File(destination + fileName));


int read = 0;
byte[] bytes = new byte[1024];

while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}

in.close();
out.flush();
out.close();

} catch (IOException e) {
System.out.println(e.getMessage());
}
}

关于tomcat - 如何使用 primefaces 在 apache tomcat 中上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27265646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com