2011-11-24 73 views
1

我想在struts1应用程序中上传文件。在struts1中上传文件

目前的实施是使用文件,像这样:

<html:file property="upload"/> 

但作为这个小工具传递文件,而不是整个文件的唯一名称这不允许上传文件,如果应用程序从远程计算机访问。

+0

文件:html:file property =“upload” - current impl – user762421

+1

您不应该对文件名感兴趣,而应该对文件内容感兴趣。另请参阅http://stackoverflow.com/questions/81180/how-to-get-the-file-path-from-html-input-form-in-firefox-3/3374408#3374408使其成为'multipart/form数据“表单。 – BalusC

+1

我不完全确定你的意思;该文件作为'ActionForm'中的'FormFile'元素可用。你能提供你认为不起作用的代码吗? –

回答

2

只使用<html:file property="upload" />不会让您的应用程序上传文件。

支持上传功能,您的表格必须由您的form bean中有ENCTYPE = “的multipart/form-data的”

<html:form action="fileUploadAction" method="post" enctype="multipart/form-data"> 
File : <html:file property="upload" /> 
<br/`> 

<html:submit /> 
</html:form`> 

,并在行动中获取文件,并对其进行操作如下

YourForm uploadForm = (YourForm) form; 
FileOutputStream outputStream = null; 
FormFile file = null; 
try { 
    file = uploadForm.getFile(); 
    String path = getServlet().getServletContext().getRealPath("")+"/"+file.getFileName(); 
    outputStream = new FileOutputStream(new File(path)); 
    outputStream.write(file.getFileData()); 
} 
finally { 
    if (outputStream != null) { 
    outputStream.close(); 
    } 
} 
+0

请不要将上传的文件保存在展开的WAR文件夹中。即使在重新启动服务器时(因为它们不包含在原始WAR文件中),重新部署WAR或某些服务器时,它们都会丢失。更甚者,当服务器配置为在内存中而不是在磁盘上扩展WAR时,getRealPath()将返回null,并且所有内容都将中断。只是不要那样做。将它们存储在固定磁盘文件系统位置中,或者存储在数据库中的最高位置。 – BalusC