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.PreparedStatement;
- 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;
- @WebServlet(name = "ImageUpload", urlPatterns = { "/ImageUpload" })
- @MultipartConfig(maxFileSize = 10 * 1024 * 1024) // max 10MB
- public class ImageUploadServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- InputStream inputStream = null;
- Part filePart = null;
- // obtains the upload file part in this multipart request
- try {
- filePart = req.getPart("image");
- } catch (Exception e) {
- System.out.println("Erreur d'upload : " + e);
- req.getRequestDispatcher("/index.jsp").forward(req, resp);
- }
- if (filePart != null) {
- // prints out some information for debugging
- System.out.println(filePart.getSubmittedFileName());
- System.out.println(filePart.getSize());
- System.out.println(filePart.getContentType());
- // obtains input stream of the upload file
- inputStream = filePart.getInputStream();
- }
- // Add to database EASY
- PreparedStatement pst = null;
- Connection conn = Connexion.getInstance();
- try {
- pst = conn.prepareStatement("INSERT INTO images VALUES(null, ?, ?, ?)");
- pst.setBinaryStream(1, inputStream);
- pst.setString(2, filePart.getSubmittedFileName());
- pst.setLong(3, filePart.getSize());
- pst.executeUpdate();
- pst.close();
- } catch (Exception e) {
- System.out.println("Exception Servlet: " + e);
- req.setAttribute("info", "Non Ajouté!");
- req.getRequestDispatcher("/index.jsp").forward(req, resp);
- return;
- }
- req.setAttribute("info", "Ajouté !");
- req.getRequestDispatcher("/index.jsp").forward(req, resp);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement