有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

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) 个答案

  1. # 1 楼答案

    您可以在数据库表中为您的Photo列创建一个默认图像,或者如果用户没有上载图像,则通过以下方式从服务器上的某个默认图像照片创建一个输入流:

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

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