【问题标题】:How to add default photo in database using servlet?如何使用 servlet 在数据库中添加默认照片?
【发布时间】:2017-05-27 14:34:05
【问题描述】:

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

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

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

【问题讨论】:

  • 欢迎来到 Stack Overflow!我编辑了您的问题,使其更简单、更容易理解。我还对您的代码进行了一些格式化,以使其看起来更好一些,但它应该更加简化,以便快速且易于喘息。您可以从中删除不重要的行,例如对ps.setString 的调用,以便其他人可以专注于重要部分。祝你好运!

标签: java mysql jsp servlets file-upload


【解决方案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

【讨论】:

  • 虽然在 MySql Blob 列中不能有默认值。所以这不是你的选择。
  • 你能把你试过的代码贴出来吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 2017-12-02
  • 2018-10-04
  • 2014-10-02
  • 2020-09-09
  • 2016-08-09
相关资源
最近更新 更多