【问题标题】:Uploading a file in struts1struts1 上传文件
【发布时间】:2012-01-05 12:22:32
【问题描述】:

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

目前实现是使用File,像这样:

<html:file property="upload"/>

但是,如果从远程计算机访问应用程序,则不允许上传文件,因为此小部件仅传递文件名而不是整个文件。

【问题讨论】:

  • 文件:html:file property="upload" - 当前实现
  • 您不应该对文件名感兴趣,而应该对文件内容感兴趣。另请参阅 stackoverflow.com/questions/81180/… 将其设为 multipart/form-data 表单。
  • 我不完全确定你的意思;该文件在ActionForm 中以FormFile 元素的形式提供。您能否提供您认为不起作用的代码?

标签: java jsp file-upload struts


【解决方案1】:

仅使用&lt;html:file property="upload" /> 不会使您的应用程序上传文件。

要支持上传功能,您的表单必须具有 enctype="multipart/form-data"

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

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

然后从表单 bean 中获取文件并按如下方式操作它

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();
  }
}

【讨论】:

  • 请不要将上传的文件保存在展开的WAR文件夹中。每当您重新部署 WAR 或在某些服务器上,即使您重新启动服务器,它们都会丢失(仅仅是因为它们不包含在原始 WAR 文件中!)。更重要的是,当服务器配置为在内存而不是磁盘中扩展 WAR 时,getRealPath() 将返回null,一切都会中断。只是不要那样做。将它们存储在固定磁盘文件系统位置或最高存储在数据库中。
猜你喜欢
  • 2014-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-17
  • 1970-01-01
  • 2016-04-02
  • 2013-07-02
相关资源
最近更新 更多