how to upload photo in database and how to retrive in jsp page

China☆狼群 提交于 2019-12-10 12:17:01

问题


I'm providing my service.xml file which contains the table details:

<entity name="Testimonial" local-service="true" remote-service="false">
    <!-- PK fields -->
    <column name="TestimonialId" type="long" primary="true" />

    <!-- UI fields -->
    <column name="subject" type="String" />
    <column name="area" type="String" />
    <column name="username" type="String" />
    <column name="email" type="String" />
    <column name="photo" type="String"/>
    <column name="company" type="String" />
    <column name="designation" type="String" />

    <!-- Audit fields -->
    <column name="createdAt" type="Date" />

Here is my java file where I have written the logic of storing data in database:

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();
    }
}

Tell me where am I wrong and what is missing?

Here is my JSP code:

<aui:form name="fm" method="POST" action="<%= updateTestiURL.toString() %>">
    <aui:input name="subject" label="Subject"/>
    <aui:input type="textarea" name="area" label="your Testimonial" />

    <aui:input name="username" label="Username"/>
    <aui:input name="email" label="Email"/>
    <aui:input type="file" label="upload your file"  name="filePath" />
    <aui:input name="company" label="Company"/>
    <aui:input name="designation" label="Designation"/>

    <aui:button type="submit" value="Save"/>

回答1:


I don't think it's a good idea to store the image's Path. Even if you had them uploaded from one and only computer, and you could access that path and work with full paths, which is probably not your case.

Since you can get a java.io.File, you can retrieve an InputStream, and work with bytes[] and store them either as Text/String or something equivalent to a Blob.

You can check in Liferay's source for ImageLocalServiceImpl class and see how it's working with these resources

Edit : a hint to get InputStream

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



回答2:


can accomplish this task using servlet... this is my form.jsp file

html>
<body>  
        <form id="staff_feedbackform"  method="post" action="uploadServlet" enctype="multipart/form-data" class="register">
        Select Photo:<input type="file" name="photo">
        <p><label> NAME:</label><input type="text"  name="name" /></p>
        <p><label>EMPLOYEE ID:</label><input type="text" name="id"/></p>
        <p><label>E-MAIL ID:</label><input type="email" name="email"></p>
        <p><label><input id="gobutton" type="submit" value="SUBMIT" class="submit" />  </label></p>
        </form>
</body>    

This is my servlet file

  @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();
    }
}
}

Table structure for table 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;

and this is my servlet mapping code include web.xml

  <servlet>
    <servlet-name>uploadServlet</servlet-name>
    <servlet-class>com.servlet.FileUploadDBServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>uploadServlet</servlet-name>
    <url-pattern>/uploadServlet</url-pattern>
  </servlet-mapping>

this is retrieving part of image and this is my show_image.jsp

<%
String id="1250";
session.setAttribute("num", id);
%>
  <body>
  <image src="display.jsp" border="0" height="200px" width="200px" alt="NO PIC"/>
  </body>

and here i am externally referencing image through dispaly.jsp file

  <% 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();
                                                             }
                      }
    %> 


来源:https://stackoverflow.com/questions/16060659/how-to-upload-photo-in-database-and-how-to-retrive-in-jsp-page

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!