简体   繁体   English

如何从JSP中的“零件”类型文件中提取文件名?

[英]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. 我想将以HTML表单提交的图像文件名保存在数据库中,因为它是学生ID。

So, I first get the image file from the HTML form using: 因此,我首先使用以下方法从HTML表单获取图像文件:

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

However, when I use filePart.getName(); 但是,当我使用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> . 我刚得到"photo" ,它是HTML形式的输入标签的名称- <td><input type="file" name="photo" size="50"/></td>

And if I use filePart.getSubmittedFileName(); 如果我使用filePart.getSubmittedFileName(); I get the entire path like: C:\\Users\\bnbih\\Pictures\\testo.jpg . 我得到的完整路径如下: C:\\Users\\bnbih\\Pictures\\testo.jpg

Is there a way to get the file name only? 有没有办法只获取文件名? which is "testo" 这是“ testo”

This is my JSP file for reference. 这是我的JSP文件供参考。

/**
 *
 * @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). 如果您在发送上传请求时在客户端上查看了一些开发工具(我更喜欢Chrome),您会注意到在其标头中可能与每个文件关联了2个项目(多部分的每个部分都有其自己的标头和正文)。 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. 第一个是名称,众所周知,它标识表单字段ID,第二个是文件名,由浏览器提交,因为文件名不是文件的一部分,而是文件系统的属性,需要额外发送。 You can get this information by calling getSubmittedFileName() if you are using servlet API 3.1, or parse it yourself. 如果您使用的是Servlet API 3.1,则可以通过调用getSubmittedFileName()来获取此信息,或者自己解析它。

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. 但是有很多库只能解析文件名,例如Java 7 Path Paths.get(filePart.getSubmittedFileName()).getFileName().toString()就足够了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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