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

时间:2016-08-10 12:01:49

标签: java html jsp post filenames

我想将HTML表单中提交的图像文件名保存在数据库中,因为它是学生ID。

所以,我首先使用以下方法从HTML表单中获取图像文件:

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

但是,当我使用filePart.getName();时,我只会得到"photo"这是HTML表单中输入标记的名称 - <td><input type="file" name="photo" size="50"/></td>

如果我使用filePart.getSubmittedFileName();,我会得到完整的路径:C:\Users\bnbih\Pictures\testo.jpg

有没有办法只获取文件名?这是“testo”

这是我的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>");
        }
    }

}

2 个答案:

答案 0 :(得分:3)

如果您在发送上传请求时在客户端上查看一些开发工具(我更喜欢Chrome),您可以注意到在其标题中每个文件可能有2个项目(multipart的每个部分都有自己的标题和正文) )。首先是name,你已经知道了表单字段ID,第二个是由浏览器提交的文件名,因为文件名不是文件的一部分,而是需要额​​外发送的文件系统的属性。如果您使用的是servlet API 3.1,则可以通过调用getSubmittedFileName()来获取此信息,或者自己解析它。

只是一点警告,并非每个浏览器都发送相同的信息,因为我相信有些人会发送整个文件路径。但是有很多库可以解析文件名,例如Java 7 Path Paths.get(filePart.getSubmittedFileName()).getFileName().toString()就足够了。

答案 1 :(得分:0)

这是在没有路径或扩展名的情况下获取文件名本身完全解决了我的问题的方法。

def build_toc_entry(left_text, right_text, available_width, text_size)
  left_text_width = font(YOUR_FONT).compute_width_of(left_text, size: text_size)
  right_text_width = font(YOUR_FONT).compute_width_of(right_text, size: text_size)
  dot_width = font(YOUR_FONT).compute_width_of('.', size: text_size)
  space_width = font(YOUR_FONT).compute_width_of(' ', size: text_size)

  space_for_dots = available_width - left_text_width - right_text_width - space_width * 2
  dots = '.' * (space_for_dots / dot_width)

  "#{left_text} #{dots} #{right_text}" # return the finished toc entry
end

text 'Locate the information on the page indicated.'
text build_toc_entry('Leader Dots', '3', 350, 8)
text build_toc_entry('Dingbats', '5', 350, 8)
text build_toc_entry('Bullets', '8', 350, 8)