Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.IOException;
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.MultipartConfig;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.Part;
- @SuppressWarnings("serial")
- @WebServlet("/upload")
- @MultipartConfig(maxFileSize = 16177215)
- public class FileUploadDBServlet extends HttpServlet {
- private String dbURL = "jdbc:oracle:thin:@localhost:1521:xe";
- private String dbUser = "system";
- private String dbPass = "system";
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- String fileId = request.getParameter("fileId");
- String fieldName = request.getParameter("fieldName");
- InputStream inputStream = null;
- Part filePart = request.getPart("fileData");
- if (filePart != null) {
- System.out.println(filePart.getName());
- System.out.println(filePart.getSize());
- System.out.println(filePart.getContentType().equals("application/pdf"));
- // obtains input stream of the upload file
- inputStream = filePart.getInputStream();
- }
- Connection conn = null;
- String message = null;
- try {
- // connects to the database
- DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
- conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
- // constructs SQL statement
- String sql = "INSERT INTO filetable (fileId, fieldName, fileData) values (?, ?, ?)";
- PreparedStatement statement = conn.prepareStatement(sql);
- statement.setString(1, fileId);
- statement.setString(2, fieldName);
- if (inputStream != null) {
- // fetches input stream of the upload file for the blob column
- statement.setBlob(3, inputStream);
- }
- // sends the statement to the database server
- int row = statement.executeUpdate();
- if (row > 0) {
- message = "File uploaded and saved into database";
- }
- } catch (SQLException ex) {
- message = "ERROR: " + ex.getMessage();
- ex.printStackTrace();
- } finally {
- if (conn != null) {
- // closes the database connection
- try {
- conn.close();
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- }
- // sets the message in request scope
- request.setAttribute("Message", message);
- // forwards to the message page
- getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement