[英]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.