JSP简单文件上传至数据库(图片上传)

  • Post author:
  • Post category:其他


涉及工具:IDEA、MYSQL

要求:在本地文件夹中选则图片上传并保存在数据库中。

实现思路:通过

input

标签

file

属性进行图片上传,通过js解析图片,发送到服务器对图片进行数据库保存。

SQL:

-- 创建图片数据库:fileImages
CREATE DATABASE fileImages;
-- 图片表
DROP TABLE images;
CREATE TABLE images(
	id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT '图片编号',
	`image` LONGTEXT COMMENT '图片'
);

JSP:

<%@ page contentType = "text/html;charset=UTF-8" language = "java" %>
<html>
    <head>
        <title>图片上传</title>
        <script>
            function  imageUpload(files){
                //创建文件读取对象
                const reader = new FileReader();
                //文件按照该格式进行读取(格式可按照需求写)
                reader.readAsDataURL(files[0], `utf-8`);
                // 读取完文件之后会回来这里
                reader.onload = (file) => {
                    // 读取文件内容
                    const image = file.target.result;
                    //设置图片预览
                    document.getElementById("onload_image").setAttribute("src", image);
                    //将解析图片存至隐藏文本域内
                    document.getElementById("image").innerText = image;
                }
            }
        </script>
    </head>
    <body>  
        <%--设置表单提交地址--%>
        <form action = "ImagesUploadServlet?method=imagesUpload" method="post">
            <input type = "file" onchange = "imageUpload(this.files)" id="upload_image">
            <img src = "" alt = "无法加载" id="onload_image">
            <textarea hidden name="image"id="image"></textarea>
            <input type = "submit" value="提交">
        </form>
    </body>
</html>

servlet:

@WebServlet(name = "ImagesUploadServlet", value = "/ImagesUploadServlet")
public class ImagesUploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if ("imagesUpload".equals(method)){
            imagesUpload(request,response);
        }
    }

    private void imagesUpload(HttpServletRequest req, HttpServletResponse resp) {
        String image = req.getParameter("image");//拿到解析图片内容
        //之后按照数据库操作就行了
    }
}



版权声明:本文为weixin_61880944原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。