[英]How to extract file name from a “Part” type file in JSP?
我想將以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>");
}
}
}
如果您在發送上傳請求時在客戶端上查看了一些開發工具(我更喜歡Chrome),您會注意到在其標頭中可能與每個文件關聯了2個項目(多部分的每個部分都有其自己的標頭和正文)。 第一個是名稱,眾所周知,它標識表單字段ID,第二個是文件名,由瀏覽器提交,因為文件名不是文件的一部分,而是文件系統的屬性,需要額外發送。 如果您使用的是Servlet API 3.1,則可以通過調用getSubmittedFileName()
來獲取此信息,或者自己解析它。
只是一點警告,並不是每個瀏覽器都發送相同的信息,因為我相信有些瀏覽器會發送整個文件路徑。 但是有很多庫只能解析文件名,例如Java 7 Path Paths.get(filePart.getSubmittedFileName()).getFileName().toString()
就足夠了。
這是從沒有路徑或擴展名的文件名本身完全解決了我的問題的方法。
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.