【问题标题】:how to get uploaded file within jsp scriptlet如何在jsp scriptlet中获取上传的文件
【发布时间】:2016-05-03 22:13:49
【问题描述】:

我正在尝试使用 request.getparameter("filename") 访问 jsp scriptlet 中上传的文件,并返回“null”。请让我知道如何使用 jsp 本身在 scriptlet 中获取文件

【问题讨论】:

    标签: jsp file-upload


    【解决方案1】:

    我猜你已经知道使用 scriptlet 被认为是一种罪过。 How to avoid Java code in JSP files? 我将在此演示中使用一个。不建议将上传的文件存储在 Web 应用程序中。 How to upload files to server using JSP/Servlet? 我将在这个演示中做到这一点。 这是我们可以用来上传文件的文件(放在您的网络应用的根文件夹中)。

    <html>
        <body>
            <form action="uploadJSP" method="post" enctype="multipart/form-data">
                <input type="file" name="myFile" />
                <input type="submit" />
            </form>
        </body> 
    </html>
    

    action 属性指向在 web.xml 文件中为我们的 JSP 提供的 servlet 名称。我们必须这样做,因为我们希望 Servlet 容器来处理我们的多部分请求。在我们的网络应用程序的 web.xml 文件中,我们应该包含类似

    的内容
    <servlet>   
                   <servlet-name>uploadfile</servlet-name>
                   <jsp-file>/uploadFile.jsp</jsp-file>
                   <multipart-config>
                       <location>/temp</location>
                       <max-file-size>20848820</max-file-size>
                       <max-request-size>418018841</max-request-size>
                       <file-size-threshold>1048576</file-size-threshold>
                   </multipart-config>
    </servlet>
    <servlet-mapping>
                    <servlet-name>uploadfile</servlet-name>
                    <url-pattern>/uploadJSP</url-pattern>
    </servlet-mapping>
    

    这里是uploadFile.jsp 把它放在你的web 应用程序的根文件夹中。

    <%@ page import="java.io.*,java.nio.file.*" %>
    <%
        Part part = request.getPart("myFile");
        String submittedName = part.getSubmittedFileName();
        String fileName = new File(submittedName).getName();
        String folder = application.getRealPath("/fileUploads");
        Path path = FileSystems.getDefault().getPath(folder, fileName);
        Files.copy(part.getInputStream(), path);
    %>
    The file <%=fileName%> was uploaded to the <%=folder%> folder.
    

    如果您有任何问题,请发布。如果您收到抱怨临时文件夹的错误,请继续并在您的容器正在寻找它的任何地方创建一个。我的 Tomcat 想要它在它的工作文件夹中。在 Web 应用的根文件夹中创建一个 fileUploads 文件夹。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 2012-08-25
      • 2014-05-10
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多