Advertisement
Guest User

Untitled

a guest
Dec 20th, 2014
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. public class UploadServlet extends HttpServlet {
  2. private static final long serialVersionUID = 1L;
  3.  
  4. public int generateRandomNumber(int start, int end) {
  5. Random random = new Random();
  6. long fraction = (long) ((end - start + 1) * random.nextDouble());
  7. return ((int) (fraction + start));
  8. }
  9.  
  10. protected void doPost(HttpServletRequest request,
  11. HttpServletResponse response) throws ServletException, IOException {
  12. // gets values of text fields
  13. String id_Przedmiotu = request.getParameter("ID");
  14.  
  15. InputStream inputStream = null; // input stream of the upload file
  16. int liczba = generateRandomNumber(1000, 8888);
  17. // obtains the upload file part in this multipart request
  18. Part filePart = request.getPart("photo");
  19. if (filePart != null) {
  20. // prints out some information for debugging
  21. System.out.println(filePart.getName());
  22. System.out.println(filePart.getSize());
  23. System.out.println(filePart.getContentType());
  24.  
  25. // obtains input stream of the upload file
  26. inputStream = filePart.getInputStream();
  27. }
  28.  
  29. Connection conn = null; // connection to the database
  30. String message = null; // message will be sent back to client
  31.  
  32. try {
  33. // connects to the database
  34. DriverManager.registerDriver(new com.mysql.jdbc.Driver());
  35. conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/elearning", "root", "");
  36. // constructs SQL statement
  37.  
  38. String sql = "INSERT INTO dokumentyprzedmiotu (ID_Dokumentu, ID_Przedmiotu, adress) values (?, ?, ?)";
  39. PreparedStatement statement = conn.prepareStatement(sql);
  40. statement.setInt(1, liczba);
  41. statement.setString(2, id_Przedmiotu);
  42.  
  43. statement.setBlob(3, inputStream);
  44.  
  45. int row = statement.executeUpdate();
  46. if (row > 0) {
  47. System.out.println("A contact was inserted with photo image.");
  48. }
  49. conn.close();
  50. } catch (SQLException ex) {
  51. ex.printStackTrace();
  52. } finally {
  53. if (conn != null) {
  54. // closes the database connection
  55. try {
  56. conn.close();
  57. } catch (SQLException ex) {
  58. ex.printStackTrace();
  59. }
  60. }
  61. System.out.println(message);
  62. response.sendRedirect("success.jsp");
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement