我如何通过 servlet 将文件上传到带有 blob 对象的数据库中

how can i upload files throw servlet into datebase with blob objcet

我想上传一些文件并将我的网站放入数据库。在上传页面中,我使用了一些这样的字段:

<form method = "post" action="addResumeSvl">
   <input type = "file" name="file1">
   <input type = "file" name="file2">
</form>

但是在addResumeSvl中,如何区分file1和file2,比如request.getParameter()方法,然后用blob对象将它们放入datebase

在您的表单中,它们必须是 multipart

<form action="addResumeSvl" method="post" enctype="multipart/form-data">

现在在 post 方法中添加以下代码段

InputStream inputStream = null; // input stream of the upload file

    // obtains the upload file part in this multipart request
    Part filePart = request.getPart("file1");
    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();
    }

现在要存储在数据库中使用下面的代码片段

DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        conn = DriverManager.getConnection(dbURL, dbUser, dbPass);

        // constructs SQL statement
        String sql = "INSERT INTO tablename(columnname) values (?)";
        PreparedStatement statement = conn.prepareStatement(sql);             
        if (inputStream != null) {
            // fetches input stream of the upload file for the blob column
            statement.setBlob(1, inputStream);
        }

        // sends the statement to the database server
        int row = statement.executeUpdate();
        if (row > 0) {
            message = "File uploaded and saved into database";
        }

file2 文件

的方法相同

在提交请求之前,请确保将 enctype="multipart/form-data 作为属性添加到 <form> 标签。

<form action="upload" method="post" enctype="multipart/form-data">
  <input type = "file" name="file1">
  <input type = "file" name="file2">
  <input type="submit" />
</form>

如果您使用的是 servlet 3.0 或更新版本,您可以使用 HttpServletRequest#getPart() 来收集多部分表单数据。

@MultipartConfig
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part file1 = request.getPart("file1"); //get your file1
        Part file2 = request.getPart("file2"); // your file2
    }
}

将文件放入变量后,您可以将它们插入数据库。