как вставить и получить изображение, аудио и видео на сервере базы данных с помощью сервлета - PullRequest
0 голосов
/ 10 ноября 2019

Как вставить изображение без BLOB-объектов, аудио и видео из HTML в базу данных с помощью сервлета при условии, что я использую сервлет Java, который подключен к MySQL, и извлекаю аудио, изображения и видео, загруженные пользователем. Я также хочу извлечь из базы данных и показать в браузере, что пользователь может играть. Пожалуйста, помогите мне с правильным решением.

ниже приведен код для вставки изображения в базу данных с помощью сервлета. Я сохранил изображение в виде капли, которая не рекомендуется. Мне нужен альтернативный способ хранения изображения вместе с некоторыми аудио и видео файлами.

ImageServlet.java

package com.image.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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;

@WebServlet("/image")
@MultipartConfig(maxFileSize = 16177215)
public class ImageServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         final int BUFFER_SIZE = 4096;

        InputStream inputStream = null; 

        Part filePart = req.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
            //the InputStream will point to a stream that contains
            //the contents of the file
            inputStream = filePart.getInputStream();
        }

        Connection con = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

try {

            Class.forName("com.mysql.jdbc.Driver");

            String dburl="jdbc:mysql://localhost:3306/employee_db";
            con=DriverManager.getConnection(dburl,"root","root");

            String sql = "INSERT INTO image_tutor values(?)";
            pstmt=con.prepareStatement(sql);
            if (inputStream != null) {
                //files are treated as BLOB objects in database
                //here we're letting the JDBC driver
                //create a blob object based on the
                //input stream that contains the data of the file
                pstmt.setBlob(1, inputStream);
            }
            //sends the statement to the database server
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println( "File uploaded and saved into database");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(pstmt!=null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }//if block
        }//finally block
    }//doPost block
}//class block

image.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="./image" method="post" enctype="multipart/form-data">
    <input type="file" name="photo" size="50" placeholder="Upload Your Image" required/><br><br>
            <input type="submit" value="Save">
</form>
</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...