0

service.xmlテーブルの詳細を含むファイルを 提供しています:

<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" />

データベースにデータを保存するロジックを記述した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="<%= 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"/>
4

2 に答える 2

1

画像のパスを保存するのは良い考えではないと思います。唯一のコンピューターからアップロードした場合でも、そのパスにアクセスして完全なパスで作業できますが、これはおそらくあなたの場合ではありません。

java.io.File を取得できるため、InputStream を取得し、bytes[] を操作して、Text/String または Blob に相当するものとして保存できます。

ImageLocalServiceImpl クラスの Liferay のソースをチェックインして、これらのリソースがどのように機能しているかを確認できます。

編集:InputStreamを取得するためのヒント

            InputStream str = (InputStream)uploadRequest.getFileAsStream("filePath", false);
于 2013-04-18T07:07:49.923 に答える
0

サーブレットを使用してこのタスクを達成できます...これは私のform.jspファイルです

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>    

これは私のサーブレットファイルです

  @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;

これは私のサーブレットマッピングコードで、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>

これは画像の一部を取得しており、これは私の 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>

ここで、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();
                                                             }
                      }
    %> 
于 2014-05-29T07:20:57.400 に答える