在JSP編程中,常常需要上傳文件到數據庫中,以實現數據的方便管理。下面,我們將介紹如何使用JSP將文件上傳到MySQL數據庫中。
首先,我們需要在JSP頁面中設置表單,以便用戶能夠瀏覽文件并上傳到服務器上:
<form action="upload.jsp" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file" /> <input type="submit" name="submit" value="上傳" /> </form>
接下來,我們需要編寫upload.jsp頁面,用于實現文件上傳并存儲到MySQL數據庫中:
<%! Connection conn = null; PreparedStatement ps = null; String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/test?useSSL=false"; String user = "username"; String password = "password"; public void init() { try { Class.forName(driver); conn = DriverManager.getConnection(url, user, password); } catch (Exception e) { e.printStackTrace(); } } %> <%@ page contentType="text/html; charset=utf-8" %> <%! public String uploadFile(HttpServletRequest request) throws Exception { String fileName = ""; String savePath = request.getServletContext().getRealPath("/upload"); File file = new File(savePath); if (!file.exists() && !file.isDirectory()) { System.out.println("目錄不存在,創建目錄成功:" + file.mkdirs()); } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> list = upload.parseRequest(request); for (FileItem item:list) { if (item.isFormField()) { continue; } fileName = item.getName(); if (fileName == null || fileName.trim().equals("")) { continue; } fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); String fileExtName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); InputStream in = item.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = in.read(buffer)) >0) { out.write(buffer, 0 ,len); } byte[] fileBytes = out.toByteArray(); ps = conn.prepareStatement("insert into file (name,data) values (?,?)"); ps.setString(1, fileName); ps.setBytes(2, fileBytes); ps.executeUpdate(); in.close(); out.close(); item.delete(); } return fileName; } %> <% String fileName = uploadFile(request); response.getWriter().write("上傳的文件名為:" + fileName); conn.close(); %>
在上面的示例代碼中,我們使用了JDBC驅動連接MySQL數據庫,并使用PreparedStatement對象將文件名和文件內容插入到文件表中。
通過以上步驟,我們便可以通過JSP將文件上傳到MySQL數據庫中,實現數據的方便管理。
上一篇jsp上傳圖片mysql
下一篇lua獲取mysql