【问题标题】:Struts2 file upload and saveStruts2文件上传和保存
【发布时间】:2013-10-02 20:08:27
【问题描述】:

我已经在 Struts2 中成功上传了一个文件,代码如下:

String filePath = servletRequest.getSession().getServletContext().getRealPath("/") + "WEB-INF\\files\\";
            fileToCreate = new File(filePath, getUserDocFileName());

            FileUtils.copyFile(this.userDoc, fileToCreate);

问题是文件被复制到 \build\web\WEB-INF\files 文件夹。现在,当我尝试使用结果类型流检索文件时:

String filePath = servletRequest.getSession().getServletContext().getRealPath("/") + "WEB-INF\\files\\";
File file = new File(filePath + getFileName());
            try {
                inputStream = new DataInputStream(new FileInputStream(file));
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



<action name="loadFile" class="com.app.Controller" method="loadFile">
            <result name="success" type="stream">
                <param name="contentType">${fileType}</param>
                <param name="inputName">inputStream</param>
                <param name="contentDisposition">inline;filename="${fileName}"</param>
                <param name="bufferSize">1024</param>
            </result>
            <interceptor-ref name="defaultStack"/>
        </action>

我得到以下异常:

java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name="inputName"> tag specified for this action.

关于这个问题的任何帮助?

FileUtils.copyFile 方法是否与设置struts.multipart.saveDir 属性相同?

如何将文件放在 WEB-INF 文件夹而不放在 build 文件夹中?

当我再次构建我的项目时,不应删除这些文件。我想稍后将它部署到 OpenShift。

【问题讨论】:

  • 您能指定WEB-INF以外的其他位置吗?
  • @RomanC 我希望文件不能从任何地方访问。这就是我将它们保存在 WEB-INF 下的原因。如果文件可以在外面安全,那么我会这样做
  • 我认为你错了,它可以从任何具有文件访问权限的地方访问,但你的应用程序可以访问它。
  • @RomanC 我的意思是没有人能够像app.com/WEB-INF/file.doc这样通过浏览器访问该文件
  • 您可能缺少inputStream 的getter/setter 和/或没有使用java.io.InputStream 类。

标签: java file-upload struts2 openshift


【解决方案1】:

尝试从 servlet 上下文中获取它

InputStream is = ServletActionContext.getServletContext().getResourceAsStream("/WEB-INF/files/" + fileName);

【讨论】:

  • 如何设置 ${fileType} 和 ${fileName}?
  • 为属性contentTypefileName 创建getter 和setter,这是struts2 文件上传还是servlet?
  • 别介意这是文件下载,我刚刚发现它们是结果的动态参数,需要getter。这不是 EL 表达式。
  • 你应该把它命名为filedownload,因为你没有上传,fileupload的工作方式不同。
  • 是的,但是如何从 InputStream 中获取 File 对象?我应该重新创建文件吗?我需要 FileName 和 contentType 的 File 对象,因为这些参数会根据文件而变化
猜你喜欢
  • 2012-01-09
  • 1970-01-01
  • 2012-12-09
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多