2016-08-10 9 views
0

학생 ID이므로 HTML 양식에 제출 된 이미지 파일 이름을 데이터베이스에 저장하려고합니다.JSP의 "부품"유형 파일에서 파일 이름을 추출하는 방법은 무엇입니까?

그래서, 내가 먼저 사용하여 HTML 양식에서 이미지 파일을 얻을 :

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

을하지만, 난 그냥 HTML 양식에 입력 태그의 이름입니다 "photo" 얻을 filePart.getName();를 사용하는 경우 - <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

, 당신은 헤더의 각 파일 asociated이 개 항목은 아마이 있다는 것을 알 수 있습니다 (다중의 각 부분이있다 그 자신의 머리글과 본문). 첫 번째 이름은 이미 알고있는 바와 같이 양식 필드 ID를 식별하고, 두 번째는 파일 이름으로, 브라우저가 제출합니다. 파일 이름은 파일의 일부가 아니며 추가로 보내야하는 파일 시스템의 속성이기 때문입니다. 서블릿 API 3.1을 사용하고 있거나 직접 파싱하는 경우 getSubmittedFileName()을 호출하여이 정보를 얻을 수 있습니다.

일부 경고는 모든 브라우저가 동일한 정보를 전송하지는 않지만 일부는 전체 파일 경로를 전송한다고 생각합니다. 그러나 파일 이름을 구문 분석 할 수있는 라이브러리가 많이 있습니다. 예를 들어 Java 7 Path Paths.get(filePart.getSubmittedFileName()).getFileName().toString()이면 충분합니다.

+0

감사합니다. 나는 또한 내 대답에 포함시킬 방법으로 코드를 사용 했으므로 확장을 제거하려고했다. 다른 사람에게는 같은 요구가있다. – Sei

0

이것은 경로 또는 확장자없이 파일 이름 자체를 가져 오는 관점에서 완전히 내 문제를 해결하는 방법입니다.

protected String getFileName(Part p){ 

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

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

return GUID; 
    } 
관련 문제