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";
}
同樣的方式做您提交請求,請確保您添加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
}
}
將文件變成變量後,可以將它們插入到數據庫中。