Advertisement
Guest User

ImageUploadServlet

a guest
Dec 15th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1.  
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.sql.Connection;
  5. import java.sql.PreparedStatement;
  6.  
  7. import javax.servlet.ServletException;
  8. import javax.servlet.annotation.MultipartConfig;
  9. import javax.servlet.annotation.WebServlet;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.servlet.http.Part;
  14.  
  15. @WebServlet(name = "ImageUpload", urlPatterns = { "/ImageUpload" })
  16. @MultipartConfig(maxFileSize = 10 * 1024 * 1024) // max 10MB
  17. public class ImageUploadServlet extends HttpServlet {
  18.     private static final long serialVersionUID = 1L;
  19.  
  20.     @Override
  21.     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  22.  
  23.         InputStream inputStream = null;
  24.         Part filePart = null;
  25.         // obtains the upload file part in this multipart request
  26.         try {
  27.             filePart = req.getPart("image");
  28.         } catch (Exception e) {
  29.             System.out.println("Erreur d'upload : " + e);
  30.             req.getRequestDispatcher("/index.jsp").forward(req, resp);
  31.         }
  32.         if (filePart != null) {
  33.             // prints out some information for debugging
  34.             System.out.println(filePart.getSubmittedFileName());
  35.             System.out.println(filePart.getSize());
  36.             System.out.println(filePart.getContentType());
  37.  
  38.             // obtains input stream of the upload file
  39.             inputStream = filePart.getInputStream();
  40.         }
  41.        
  42.         // Add to database EASY
  43.         PreparedStatement pst = null;
  44.         Connection conn = Connexion.getInstance();
  45.  
  46.         try {
  47.             pst = conn.prepareStatement("INSERT INTO images VALUES(null, ?, ?, ?)");
  48.  
  49.             pst.setBinaryStream(1, inputStream);
  50.             pst.setString(2, filePart.getSubmittedFileName());
  51.             pst.setLong(3, filePart.getSize());
  52.             pst.executeUpdate();
  53.             pst.close();
  54.         } catch (Exception e) {
  55.             System.out.println("Exception Servlet: " + e);
  56.             req.setAttribute("info", "Non Ajouté!");
  57.             req.getRequestDispatcher("/index.jsp").forward(req, resp);
  58.             return;
  59.         }
  60.  
  61.         req.setAttribute("info", "Ajouté !");
  62.         req.getRequestDispatcher("/index.jsp").forward(req, resp);
  63.     }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement