Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

how to get uploaded file within jsp scriptlet

I am trying to access a uploaded file within jsp scriptlet using request.getparameter("filename") and its returning 'null'. Please let me know how to get the file in scriptlet using jsp itself

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I guess you already know that using scriptlets is considered a sin. How to avoid Java code in JSP files? I will use one for this demonstration. Storing uploaded files within the web app is not recommended. How to upload files to server using JSP/Servlet? I will do it in this demonstration. Here is a file(put in your web app's root folder) that we can use to upload a file.

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

The action attribute points to the servlet name given to our JSP in our web.xml file. We must do this because we want the Servlet container to handle our multipart request. In our web app's web.xml file, we should include something like

<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>

Here is uploadFile.jsp put it your web app's root folder.

<%@ 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.

If you have any problems, then post them. If you get an error that complains about the temp folder, just go ahead and create one wherever your container is looking for it. My Tomcat wanted it in it's work folder. Create a fileUploads folder in your web app's root folder.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...