Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class UploadServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- public int generateRandomNumber(int start, int end) {
- Random random = new Random();
- long fraction = (long) ((end - start + 1) * random.nextDouble());
- return ((int) (fraction + start));
- }
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- // gets values of text fields
- String id_Przedmiotu = request.getParameter("ID");
- InputStream inputStream = null; // input stream of the upload file
- int liczba = generateRandomNumber(1000, 8888);
- // 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();
- }
- Connection conn = null; // connection to the database
- String message = null; // message will be sent back to client
- try {
- // connects to the database
- DriverManager.registerDriver(new com.mysql.jdbc.Driver());
- conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/elearning", "root", "");
- // constructs SQL statement
- String sql = "INSERT INTO dokumentyprzedmiotu (ID_Dokumentu, ID_Przedmiotu, adress) values (?, ?, ?)";
- PreparedStatement statement = conn.prepareStatement(sql);
- statement.setInt(1, liczba);
- statement.setString(2, id_Przedmiotu);
- statement.setBlob(3, inputStream);
- int row = statement.executeUpdate();
- if (row > 0) {
- System.out.println("A contact was inserted with photo image.");
- }
- conn.close();
- } catch (SQLException ex) {
- ex.printStackTrace();
- } finally {
- if (conn != null) {
- // closes the database connection
- try {
- conn.close();
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- }
- System.out.println(message);
- response.sendRedirect("success.jsp");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement