如何在数据库中上传照片以及如何在jsp页面中进行检索

我正在提供包含表详细信息的service.xml文件:

              

这是我的java文件,我在其中编写了在数据库中存储数据的逻辑:

 public void updateTesti(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException, PortletException { String subject = ParamUtil.getString(actionRequest,"subject"); String area = ParamUtil.getString(actionRequest,"area"); String username = ParamUtil.getString(actionRequest,"username"); String email = ParamUtil.getString(actionRequest,"email"); String company = ParamUtil.getString(actionRequest,"company"); String designation = ParamUtil.getString(actionRequest,"designation"); System.out.println("Your inputs ==> " + subject + ", " + area + "," + username + "," + email + "," + company + "," + designation); Testimonial T1 = new TestimonialImpl(); // set primary key long TestimonialId = 0L; try { TestimonialId = CounterLocalServiceUtil.increment( this.getClass().getName()); } catch (SystemException e) { e.printStackTrace(); } T1.setTestimonialId(TestimonialId); UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest); String filePath = uploadRequest.getFileName("filePath"); try{ java.io.File file = uploadRequest.getFile("filePath"); //Manage the Upload }catch (Exception e) { /// } // set UI fields T1.setSubject(subject); T1.setArea(area); T1.setUsername(username); T1.setEmail(email); T1.setCompany(company); T1.setDesignation(designation); T1.setPhoto(filePath); // set audit field(s) T1.setCreatedAt(new Date()); // insert the book using persistence api try { TestimonialLocalServiceUtil.addTestimonial(T1); } catch (SystemException e) { e.printStackTrace(); } } 

告诉我我错在哪里,缺少什么?

这是我的JSP代码:

 <aui:form name="fm" method="POST" action="">         

我不认为存储图像的路径是个好主意。 即使您从一台计算机上传了它们,也可以访问该路径并使用完整路径,这可能不是您的情况。

因为你可以得到一个java.io.File,你可以检索一个InputStream,并使用bytes []并将它们存储为Text / String或类似于Blob的东西。

您可以在Liferay的ImageLocalServiceImpl类的源代码中查看它,看看它是如何使用这些资源的

编辑:提示输入InputStream

  InputStream str = (InputStream)uploadRequest.getFileAsStream("filePath", false); 

可以使用servlet来完成这个任务…这是我的form.jsp文件

 html>  
Select Photo:

这是我的servlet文件

  @WebServlet("/FileUploadDBServlet") @MultipartConfig(maxFileSize = 10177215) // upload file's size up to 16MB public class FileUploadDBServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FileUploadDBServlet() { super(); } private final String dbURL = "jdbc:mysql://localhost:3306/test"; private final String dbUser = "root"; private final String dbPass = ""; protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("name"); String id=request.getParameter("id"); String email=request.getParameter("email"); InputStream inputStream = null; // input stream of the upload file // obtains the upload file part in this multipart request Part filePart = request.getPart("photo"); if (filePart != null) { // prints out some information for debugging System.out.println(filePart.getName()); System.out.println(filePart.getSize()); System.out.println(filePart.getContentType()); // obtains input stream of the upload file inputStream = filePart.getInputStream(); } Connection conn = null; // connection to the database String message = null; // message will be sent back to client try { // connects to the database DriverManager.registerDriver(new com.mysql.jdbc.Driver()); HttpSession session=request.getSession(false); conn = (Connection) DriverManager.getConnection(dbURL,dbUser,dbPass); // constructs SQL statement Statement st=conn.createStatement(); String sql = "INSERT INTO file1(id,name,email,photo) values (?,?,?,?)"; PreparedStatement statement = conn.prepareStatement(sql); statement.setString(1,id); statement.setString(2,name ); statement.setString(3,email ); if (inputStream != null) { // fetches input stream of the upload file for the blob column statement.setBlob(4, inputStream); } // sends the statement to the database server int row = statement.executeUpdate(); if (row > 0) { message = "File uploaded and saved into database"; out.println("uploades succesfully"); System.out.println("uploades succesfully"); } } catch (SQLException ex) { System.out.println(ex); message = "ERROR: " + ex.getMessage(); } } } 

表file1的表结构

  DROP TABLE IF EXISTS `file1`; CREATE TABLE IF NOT EXISTS `file1` ( `id` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `photo` longblob NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

这是我的servlet映射代码包含web.xml

   uploadServlet com.servlet.FileUploadDBServlet 1   uploadServlet /uploadServlet  

这是检索图像的一部分,这是我的show_image.jsp

 <% String id="1250"; session.setAttribute("num", id); %>  NO PIC  

在这里我通过dispaly.jsp文件从外部引用图像

  <% Blob image = null; String no=(String)session.getAttribute("num"); byte[ ] imgData = null ; Statement stmt = null; ResultSet rs = null; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = (Connection); DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root",""); stmt = con.createStatement(); rs = stmt.executeQuery("select photo from file1 where id = '"+no+"'"); if (rs.next()) { image = rs.getBlob(1); imgData = image.getBytes(1,(int)image.length()); } else { out.println("Display Blob Example"); out.println("image not found for given id"); return; } // display the image response.setContentType("image/gif"); OutputStream o = response.getOutputStream(); o.write(imgData); o.flush(); o.close(); } catch (Exception e) { out.println("Unable To Display image"); out.println("Image Display Error=" + e.getMessage()); return; } finally { try { rs.close(); stmt.close(); } catch (SQLException e) { System.out.println(e); e.printStackTrace(); } } %>