如何使用servlet在数据库中添加默认照片?

时间:2017-01-12 13:03:47

标签: java mysql jsp servlets file-upload

如果用户没有手动上传任何照片,如何在数据库中添加默认照片?

我正在使用此代码处理用户上传的照片:

InputStream inputStream = null;

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

try
{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/busbooking","user","password");
    PreparedStatement ps=con.prepareStatement("INSERT INTO `busbooking`.`users` (`username`, `Full_name`, `email`, `password`, `Mob_no`, `DOB`, `address`, `Gender`, `Usertype`, `Agency_name`, `Photo`) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
    ps.setString(1, username);
    ps.setString(2, FullName);
    ps.setString(3, email);
    ps.setString(4, passwd);
    ps.setString(5, mobile);
    ps.setString(6, dob);
    ps.setString(7, address);
    ps.setString(8, gender);
    ps.setString(9, Usertype);
    ps.setString(10, AgencyName);
    if (inputStream != null) {
        // fetches input stream of the upload file for the blob column
        ps.setBlob(11, inputStream);
    }
    ps.executeUpdate();   

    out.println("<script>alert('Registration Successful');</script>");
    RequestDispatcher rd=request.getRequestDispatcher("LoginPage1.jsp");
    rd.include(request, response);

    ps.close();
    con.close();
}

1 个答案:

答案 0 :(得分:0)

您可以在数据库表中为 Photo 列创建默认图像,或者如果用户未上传图像,则从服务器上的某些默认图像照片创建输入流:< / p>

  File initialFile = new File("src/main/resources/sample.txt");
  InputStream targetStream = new FileInputStream(initialFile);

示例来源http://www.baeldung.com/convert-file-to-input-stream