简体   繁体   中英

How to extract file name from a “Part” type file in JSP?

I want to save the image file name submitted in the HTML form in the database as it is the student ID.

So, I first get the image file from the HTML form using:

        Part filePart = request.getPart("photo");

However, when I use filePart.getName(); I just get "photo" which is the name of the input tag in the HTML form - <td><input type="file" name="photo" size="50"/></td> .

And if I use filePart.getSubmittedFileName(); I get the entire path like: C:\\Users\\bnbih\\Pictures\\testo.jpg .

Is there a way to get the file name only? which is "testo"

This is my JSP file for reference.

/**
 *
 * @author bnbih
 */
@WebServlet(urlPatterns = {"/uploadServlet"})
@MultipartConfig(maxFileSize = 16177215)    // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {

     // database connection settings
    private String dbURL = "jdbc:mysql://server_IP:3306/db_name";
    private String dbUser = "root";
    private String dbPass = "";
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        InputStream inputstream = null;//input stream of the uploaded photo

        Part filePart = request.getPart("photo");
        if(filePart != null){

       //print out file info for debugging
       System.out.println(filePart.getName());
       System.out.println(filePart.getSize());
       System.out.println(filePart.getContentType());

       //get the file 
       inputstream = filePart.getInputStream();

        }
        Connection con = null;
        String message = null;

        try{
        //connect to the database
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        con = DriverManager.getConnection(dbURL, dbUser, dbPass);

        //construct sql statement
        String sql = "INSERT INTO StudentInfo (img, student) values (?,?)";
        PreparedStatement statement = con.prepareStatement(sql);

        if(inputstream != null){
        //fetches input stream of the upload file for the blob column
        statement.setBlob(1, inputstream);
        statement.setString(2, filePart.getSubmittedFileName());
        }

        //sends the statement to the database server
        int row = statement.executeUpdate();

        if(row > 0){
        message = "Student image uploaded successfully";
        }


        }catch(SQLException ex){
        message = "Something went wrong!! see below \n" + ex.getMessage() + filePart.getSubmittedFileName();
        }finally{
        if(con != null){
        //close db connection
        try{
        con.close();
        }catch(SQLException ex){
            ex.printStackTrace();
        }
    }

 //sets the message in request scope

 request.setAttribute("Message", message);

 // forwards to the message page
 getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);

 }




        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet FileUploadDBServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet FileUploadDBServlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

}

If you look into some dev tools (I prefer Chrome) on you client while sending upload request, you can notice that in its header there are probably 2 items asociated with each file (each part of multipart has its own header and body). First is name, which as you already know identifies form field ID, and second is filename, which is submitted by browser, since filenames are not part of the file but property of the filesystem which needs to be sent extra. You can get this information by calling getSubmittedFileName() if you are using servlet API 3.1, or parse it yourself.

Just a little warning, not every browser sends the same information, as I believe some send whole filepath. But there are plenty of libraries which can parse just the filename, for example Java 7 Path Paths.get(filePart.getSubmittedFileName()).getFileName().toString() should suffice.

This is the method that solved my problem completely in terms of getting the file name itself with no path or extension.

protected String getFileName(Part p){

String GUIDwithext = Paths.get(p.getSubmittedFileName()).getFileName().toString();

String GUID = GUIDwithext.substring(0, GUIDwithext.lastIndexOf('.'));

return GUID;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM