使用servlet将图像路径插入数据库

时间:2019-03-06 10:21:20

标签: java mysql jsp servlets

我想使用servlet将图像插入数据库。我已经在网页内创建了images文件夹,我想将其发送到该文件夹​​。这是我的代码。

CompanyReg.jsp

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="Colorlib Templates">
<meta name="author" content="Colorlib">
<meta name="keywords" content="Colorlib Templates">
<title>New Member?</title>
<link href="resources/CompanyReg/vendor/mdi-font/css/material-design-iconic-font.min.css" rel="stylesheet" media="all">
<link href="resources/CompanyReg/vendor/font-awesome-4.7/css/font-awesome.min.css" rel="stylesheet" media="all">    
<link href="https://fonts.googleapis.com/css?family=Poppins:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
<link href="resources/CompanyReg/vendor/select2/select2.min.css" rel="stylesheet" media="all">
<link href="resources/CompanyReg/vendor/datepicker/daterangepicker.css" rel="stylesheet" media="all">
<link href="resources/CompanyReg/css/main.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="resources/CompanyReg/favicon.ico">
<link rel="stylesheet" type="text/css" href="resources/CompanyReg/css/normalize.css" />
<link rel="stylesheet" type="text/css" href="resources/CompanyReg/css/demo.css" />
<link rel="stylesheet" type="text/css" href="resources/CompanyReg/css/component.css" />
</head>
<body>
 <div class="page-wrapper bg-gra-02 p-t-130 p-b-100 font-poppins">
    <div class="wrapper wrapper--w680">
        <div class="card card-4">
            <div class="card-body">
                <h2 class="title">Registration Form</h2>
                <form method="POST" action="CompanyReg" enctype='multipart/form-data'>
                    <div class="row row-space">
                        <div class="col-2">
                            <div class="input-group">
                                <label class="label">Company Name</label>
                                <input class="input--style-4" type="text" name="company_name">
                            </div>
                        </div>
                    </div>
                    <div class="row row-space">
                        <div class="col-2">
                            <div class="input-group">
                                <label class="label">Established Date</label>
                                <div class="input-group-icon">
                                    <input class="input--style-4 js-datepicker" type="text" name="est_year">
                                    <i class="zmdi zmdi-calendar-note input-icon js-btn-calendar"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row row-space">
                        <div class="col-2">
                            <div class="input-group">
                                <label class="label">Address</label>
                                <input class="input--style-4" type="text" name="address">
                            </div>
                        </div>
                        <div class="col-2">
                            <div class="input-group">
                                <label class="label">Email</label>
                                <input class="input--style-4" type="text" name="email">
                            </div>
                        </div>
                        <div class="col-2">
                            <div class="input-group">
                                <label class="label">Phone Number</label>
                                <input class="input--style-4" type="text" name="phone">
                            </div>
                        </div>
                        <div class="col-2">
                            <div class="input-group">
                                <label class="label">Password</label>
                                <input class="input--style-4" type="Password" name="password">
                            </div>
                        </div>
                        <div class="col-2">
                            <div class="input-group">
                                <label class="label">Repeat Password</label>
                                <input class="input--style-4" type="Password" name="repeatPassword">
                            </div>
                        </div>                            
                    </div>
                    <div class="col-2">
                            <div class="input-group">
                                <label class="label">Upload Company Photo</label>
                                <div class="box">
                                    <input type="file" name="photo" id="file-1" class="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple style="display: none;" />
                                    <label for="file-1"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="17" viewBox="0 0 20 17"><path d="M10 0l-5.2 4.9h3.3v5.1h3.8v-5.1h3.3l-5.2-4.9zm9.3 11.5l-3.2-2.1h-2l3.4 2.6h-3.5c-.1 0-.2.1-.2.1l-.8 2.3h-6l-.8-2.2c-.1-.1-.1-.2-.2-.2h-3.6l3.4-2.6h-2l-3.2 2.1c-.4.3-.7 1-.6 1.5l.6 3.1c.1.5.7.9 1.2.9h16.3c.6 0 1.1-.4 1.3-.9l.6-3.1c.1-.5-.2-1.2-.7-1.5z"/></svg> <span>Choose a file&hellip;</span></label>
                                </div>
                            </div>
                        </div>
                    <div class="p-t-15">
                        <button class="btn btn--radius-2 btn--blue" type="submit">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<script src="resources/CompanyReg/vendor/jquery/jquery.min.js"></script>
<script src="resources/CompanyReg/vendor/select2/select2.min.js"></script>
<script src="resources/CompanyReg/vendor/datepicker/moment.min.js"></script>
<script src="resources/CompanyReg/vendor/datepicker/daterangepicker.js"></script>
<script src="resources/CompanyReg/js/global.js"></script>
</body>
</html>

这是我的servlet代码

 package Company;

 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.PrintWriter;
 import java.sql.Connection;
 import java.sql.DriverManager;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import javax.servlet.ServletException;
 import javax.servlet.annotation.MultipartConfig;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.servlet.http.Part;
 @MultipartConfig(maxFileSize = 16177215) 
 public class CompanyReg extends HttpServlet {

private static final String SAVE_DIR ="images";
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    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 CompanyReg</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet CompanyReg at " + request.getContextPath() + "</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

// <editor-fold
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String savePath = "F:\\JAVA EE Final\\Java Final\\web" + File.separator +SAVE_DIR;
    File fileSaveDir = new File(savePath);

    String company_name = request.getParameter("company_name");
    String company_email = request.getParameter("email");
    String est_date = request.getParameter("est_year");
    String company_address = request.getParameter("address");
    String company_pasword = request.getParameter("password");
    String company_contactno = request.getParameter("phone");
    Part part = request.getPart("photo");
    String filename = extractFileName(part);
    try 
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/javanew","root","");
        PreparedStatement pst = con.prepareStatement(" insert into company (Name,Email,Est_date,Address,Password,ContactNo,Photo) values(?,?,?,?,?,?,?)");
                    pst.setString(1, company_name);
                    pst.setString(2, company_email);
                    pst.setString(3, est_date);
                    pst.setString(4, company_address);
                    pst.setString(5, company_pasword);
                    pst.setString(6, company_contactno);
                    String filePath = savePath + File.separator + filename;
                    pst.setString(7, filePath);            
        int rs=pst.executeUpdate();            
        if(rs>0)
        {
            getServletContext().getRequestDispatcher("").forward(request, response);
        }
    }
    catch (Exception e)
    {
        PrintWriter out = response.getWriter();
        out.print(e);
    }
}
@Override
public String getServletInfo() {
    return "Short description";
}
private String extractFileName(Part part) {

    String contenDisp = part.getHeader("content-disposition");
    String [] items = contenDisp.split(";");
    for (String s : items)
    {
        if (s.trim().startsWith("filename"))
        {
            return s.substring(s.indexOf("=") + 2, s.length()-1);
        }
    }
    return "";       
}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
    <servlet-name>CompanyReg</servlet-name>
    <servlet-class>Company.CompanyReg</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>CompanyReg</servlet-name>
    <url-pattern>/CompanyReg</url-pattern>
</servlet-mapping>
<session-config>
    <session-timeout>
        30
    </session-timeout>
</session-config>

</web-app>

我的数据库正确显示了路径,但是在该文件夹中看不到图像。所以请告诉我该怎么做

2 个答案:

答案 0 :(得分:2)

是,因为图像不在该文件夹中。因此,在提交表单时,您需要将图像复制到您创建的文件夹中。这是将图像复制到您的文件夹的示例代码

    public void copyFile(String fileName,String fileType, InputStream in) {

       try {


       //relativeWebPath is the path to the folder you created in your web directory
            File file = getUniqueFilename(new File(relativeWebPath+"/"+fileName));




          try ( // write the inputStream to a FileOutputStream
                  OutputStream out = new FileOutputStream(new File(relativeWebPath + "/"+file.getName()))) {
              int read = 0;
              byte[] bytes = new byte[1024];

              while ((read = in.read(bytes)) != -1) {
                  out.write(bytes, 0, read);
              }

              in.close();
              out.flush();

          }


    } catch (IOException e) {
        System.out.println(e);
    }
}

//returns a file with a unique name in case an image with the same name 
//already exist in the folder

private static File getUniqueFilename( File file )
    {
        String baseName = FilenameUtils.getBaseName( file.getName() );
        String extension = FilenameUtils.getExtension( file.getName() );
        int counter = 1;
        while(file.exists())
        {
            file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
        }
        return file;
    }

答案 1 :(得分:1)

Part filePart = request.getPart("photo"); 
//Retrieves <input type="file" name="file">


fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.


uploadedInputStream = filePart.getInputStream();

尝试此代码