how to get uploaded file within jsp scriptlet

前端 未结 1 455
孤街浪徒
孤街浪徒 2020-12-22 00:34

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 scr

1条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-22 00:59

    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.

    
        
            

    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

       
                   uploadfile
                   /uploadFile.jsp
                   
                       /temp
                       20848820
                       418018841
                       1048576
                   
    
    
                    uploadfile
                    /uploadJSP
    
    

    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.

    0 讨论(0)
提交回复
热议问题