图片服务器及测试报告

图片服务器及测试报告,第1张

图片服务器及测试报告 图片服务器项目 1.项目需求 1.1项目描述:

主要分为三大模块,上传模块,删除模块,展示模块。其中展示模块又可分为展示多张图片与放大图片。进入页面之后就可进行上传 *** 作、删除 *** 作。

1.2核心功能:

本项目主要分为两部分,数据存储部分与服务器模块,使用MySQL数据库存储图片属性,将图片内容保存在本次磁盘,服务器提供上传图片,获取图片属性,根据图片URL获取图片内容和删除图片等接口。

1.3重要知识点
  1. 简单的Web服务器设计开发能力(Servlet 的使用)
  2. 使用数据库(MySQL)JDBC *** 作 MySQL
  3. 数据库设计(根据实际场景设计数据库表结构)
  4. 前后端交互的 API 的设计(基于HTTP协议)
  5. 认识 JSON 数据格式,学习使用 Java 中的 Gson 这个库 *** 作 JSON 数据
  6. 强化 HTTP 协议的理解,学习测试 HTTP 服务器,Postman 工具的使用
  7. 基于 md5 进行校验
  8. 使用 HTML CSS Javascript 技术构建一个简单的网页
2.项目实现



代码展示:

DBUtil.java

package dao;



import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DBUtil {
    private static final String URL="jdbc:mysql://127.0.0.1:3306/image_server";
    private static final String USERNAME="root";
    private static final String PASSWORD="1231";

    private static volatile DataSource dataSource=null;

    public static DataSource getDataSource(){
        //通过此方法创建DataSource的实例
        if(dataSource==null){
            synchronized (DBUtil.class){
                if(dataSource==null){
                    dataSource=new MysqlDataSource();
                    MysqlDataSource tmpDataSource=(MysqlDataSource)dataSource;
                    tmpDataSource.setURL(URL);
                    tmpDataSource.setUser(USERNAME);
                    tmpDataSource.setPassword(PASSWORD);
                }
            }
        }
        return dataSource;
    }

    public static Connection getConnection() {
        try {
            return getDataSource().getConnection();
        } catch (SQLException exc) {
            exc.printStackTrace();
        }
        return null;
    }

    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        try {
            if(resultSet!=null){
                resultSet.close();
            }
            if(preparedStatement!=null){
                preparedStatement.close();
            }
            if(connection!=null){
                connection.close();
            }
        } catch (SQLException exc) {
            exc.printStackTrace();
        }
    }

}

Image.java

package dao;


public class Image {
    private int imageId;
    private String imageName;
    private int size;
    private String uploadTime;
    private String contentType;
    private String path;
    private String md5;

    public int getImageId() {
        return imageId;
    }

    public void setImageId(int imageId) {
        this.imageId = imageId;
    }

    public String getImageName() {
        return imageName;
    }

    public void setImageName(String imageName) {
        this.imageName = imageName;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public String getUploadTime() {
        return uploadTime;
    }

    public void setUploadTime(String uploadTime) {
        this.uploadTime = uploadTime;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getMd5() {
        return md5;
    }

    public void setMd5(String md5) {
        this.md5 = md5;
    }

    @Override
    public String toString() {
        return "Image{" +
                "imageId=" + imageId +
                ", imageName='" + imageName + ''' +
                ", size=" + size +
                ", uploadTime='" + uploadTime + ''' +
                ", contentType='" + contentType + ''' +
                ", path='" + path + ''' +
                ", md5='" + md5 + ''' +
                '}';
    }
}

ImageDao.java

package dao;

import common.JavaImageServerException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class ImageDao {

    public void insert(Image image) {
        //1.获取数据库连接
        Connection connection = DBUtil.getConnection();
        //2.创建并拼装sql语句
        String sql = "insert into image_table values(null,?,?,?,?,?,?)";
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, image.getImageName());
            statement.setInt(2, image.getSize());
            statement.setString(3, image.getUploadTime());
            statement.setString(4, image.getContentType());
            statement.setString(5, image.getPath());
            statement.setString(6, image.getMd5());

            //3.执行sql语句
            int ret = statement.executeUpdate();

            if(ret!=1){
                //程序出现问题,抛出一个异常
                throw new JavaImageServerException("插入数据库错误!");
            }

        } catch (SQLException exc) {
            exc.printStackTrace();
        } catch (JavaImageServerException e) {
            e.printStackTrace();
        }finally {
            //4.关闭连接和statement对象
            DBUtil.close(connection,statement,null);
        }
    }


    public List selectAll(){
        List images=new ArrayList();
        //1.获取数据库连接
        Connection connection=DBUtil.getConnection();
        //2.构造sql语句
        String sql="select * from image_table";
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            //3.执行sql语句
            statement=connection.prepareStatement(sql);
            resultSet=statement.executeQuery();
            //4.处理结果集
            while(resultSet.next()){
                Image image=new Image();
                image.setImageId(resultSet.getInt("imageId"));
                image.setImageName(resultSet.getString("imageName"));
                image.setSize(resultSet.getInt("size"));
                image.setUploadTime(resultSet.getString("uploadTime"));
                image.setContentType(resultSet.getString("contentType"));
                image.setPath(resultSet.getString("path"));
                image.setMd5(resultSet.getString("md5"));
                images.add(image);
            }
            return images;

        } catch (SQLException exc) {
            exc.printStackTrace();
        }finally {
            //5.关闭连接
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }


    public Image selectOne(int imageId){
        //1.获取数据库连接
        Connection connection=DBUtil.getConnection();
        //2.构造sql语句
        String sql="select * from image_table where imageId = ? ";
        //3.执行sql语句
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            statement=connection.prepareStatement(sql);
            statement.setInt(1,imageId);
            resultSet=statement.executeQuery();
            //4.处理结果集
            if(resultSet.next()){
                Image image=new Image();
                image.setImageId(resultSet.getInt("imageId"));
                image.setImageName(resultSet.getString("imageName"));
                image.setSize(resultSet.getInt("size"));
                image.setUploadTime(resultSet.getString("uploadTime"));
                image.setContentType(resultSet.getString("contentType"));
                image.setPath(resultSet.getString("path"));
                image.setMd5(resultSet.getString("md5"));

                return image;
            }

        } catch (SQLException exc) {
            exc.printStackTrace();
        }finally {
            //5.关闭连接
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }


    public void delete(int imageId){
        //1.获取数据库连接
        Connection connection=DBUtil.getConnection();
        //2.拼装sql语句
        String sql="delete from image_table where imageId=?";
        //3.执行sql语句
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            statement=connection.prepareStatement(sql);
            statement.setInt(1,imageId);
            int ret=statement.executeUpdate();
            if(ret!=1){
                throw new JavaImageServerException("删除图片失败!");
            }

        } catch (SQLException exc) {
            exc.printStackTrace();
        } catch (JavaImageServerException e) {
            e.printStackTrace();
        } finally {
            //4.关闭连接
            DBUtil.close(connection,statement,resultSet);

        }
    }


    public Image selectByMd5(String md5){
        //1.获取数据库连接
        Connection connection=DBUtil.getConnection();
        //2.构造sql语句
        String sql="select * from image_table where md5 = ? ";
        //3.执行sql语句
        PreparedStatement statement=null;
        ResultSet resultSet=null;
        try {
            statement=connection.prepareStatement(sql);
            statement.setString(1,md5);
            resultSet=statement.executeQuery();
            //4.处理结果集
            if(resultSet.next()){
                Image image=new Image();
                image.setImageId(resultSet.getInt("imageId"));
                image.setImageName(resultSet.getString("imageName"));
                image.setSize(resultSet.getInt("size"));
                image.setUploadTime(resultSet.getString("uploadTime"));
                image.setContentType(resultSet.getString("contentType"));
                image.setPath(resultSet.getString("path"));
                image.setMd5(resultSet.getString("md5"));

                return image;
            }

        } catch (SQLException exc) {
            exc.printStackTrace();
        }finally {
            //5.关闭连接
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }

}

ImageServlet.java

package api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import dao.Image;
import dao.ImageDao;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.SimpleTimeZone;


@WebServlet("/image")
public class ImageServlet extends HttpServlet{
    

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String imageId=req.getParameter("imageId");
        if(imageId==null||imageId.equals("")){
            selectAll(req,resp);
        }else{
            selectOne(imageId,resp);
        }
    }

    private void selectOne(String imageId, HttpServletResponse resp) throws IOException {

        resp.setContentType("application/json; charset=utf-8");
        ImageDao imageDao=new ImageDao();
        Image image=imageDao.selectOne(Integer.parseInt(imageId));

        Gson gson=new GsonBuilder().create();
        String jsonData=gson.toJson(image);
        resp.getWriter().write(jsonData);

    }

    private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json; charset=utf-8");
        ImageDao imageDao=new ImageDao();
        List images=imageDao.selectAll();

        Gson gson=new GsonBuilder().create();

        String jsonData=gson.toJson(images);
        resp.getWriter().write(jsonData);

    }

    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取图片的属性信息,并且存入数据库
            //a.固定格式
        FileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(factory);
            //b.通过upload对象进一步解析请求(解析HTTP请求中奇怪的body中的内容)
                //FileItem代表一个上传文件的对象
        List items=null;
        try {
            //理论上来说,http支持一个请求同时上传多个文件
            items=upload.parseRequest(req);
        } catch (FileUploadException e) {
            //解析出错
            e.printStackTrace();
            //告诉客户端出现的具体错误
            resp.setContentType("application/json; charset:utf-8");
            resp.getWriter().write("{"ok":false,"reason":"请求解析失败"}");
            return;
        }
            //c.把FileItem中的属性提取出来,转换成Image对象,才能存储到数据库中
            //当前只考虑一张图片的情况
        FileItem fileItem=items.get(0);
        Image image=new Image();
        image.setImageName(fileItem.getName());
        image.setSize((int)fileItem.getSize());

        //手动获取当前时间,并格式化日期,yyyyMMdd
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyyMMdd");
        image.setUploadTime(simpleDateFormat.format(new Date()));
        image.setContentType(fileItem.getContentType());

        image.setMd5(DigestUtils.md5Hex(fileItem.get()));
        //自己构造一个路径来保存
        image.setPath("./image/"+image.getMd5());

        ImageDao imageDao=new ImageDao();

        Image existImage=imageDao.selectByMd5(image.getMd5());

        imageDao.insert(image);

        //2.获取图片内容信息,并且写入磁盘
        if(existImage==null) {
            File file = new File(image.getPath());
            try {
                fileItem.write(file);
            } catch (Exception e) {
                e.printStackTrace();

                resp.setContentType("application/json; charset:utf-8");
                resp.getWriter().write("{"ok":false,"reason":"写入磁盘失败"}");
                return;
            }
        }

        //3.给客户端返回一个结果数据
       
        resp.sendRedirect("index.html");
    }


    
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset:utf-8");
        //1.先获取到请求中的imageId
        String imageId=req.getParameter("imageId");
        if(imageId==null||imageId.equals("")){
            resp.setStatus(200);
            resp.getWriter().write("{"ok":false,"reason":"解析请求失败"}");
            return;
        }

        //2.创建ImageDao对象,查到该图片的属性,文件路径
        ImageDao imageDao=new ImageDao();
        Image image=imageDao.selectOne(Integer.parseInt(imageId));
        if(image==null){
            resp.setStatus(200);
            resp.getWriter().write("{"ok":false,"reason":"imageId在数据库中不存在"}");
            return;
        }

        //3.删除数据库中的记录
        imageDao.delete(Integer.parseInt(imageId));
        //4.删除本地磁盘文件
        File file=new File(image.getPath());
        file.delete();
        resp.setStatus(200);
        resp.getWriter().write("{"ok":true}");

    }
}

ImageShow.java

package api;

import dao.Image;
import dao.ImageDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;



@WebServlet("/imageShow")
public class ImageShowServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.解析出imageId
        String imageId=req.getParameter("imageId");
        if(imageId==null||imageId.equals("")){
            resp.setContentType("application/json;charset:utf-8");
            resp.getWriter().write("{"ok":false,"reason":"imageId解析失败"}");
            return;
        }
        //2.根据imageId查找数据库
        ImageDao imageDao=new ImageDao();
        Image image=imageDao.selectOne(Integer.parseInt(imageId));
        //3.根据路径打开文件,读取其中内容,写入到响应对象中
        resp.setContentType(image.getContentType());
        File file=new File(image.getPath());

        //由于图片为二进制文件,应该使用字节流方式读取文件
        OutputStream outputStream=resp.getOutputStream();
        FileInputStream fileInputStream=new FileInputStream(file);
        byte[] buffer=new byte[1024];
        while(true){
            int len=fileInputStream.read(buffer);
            if(len==-1){
                break;
            }
            //此时已经读到一部分数据,放入buffer中
            outputStream.write(buffer);
        }
        fileInputStream.close();
        outputStream.close();
    }
}

index.html




  
  
  
  
  
  CY 图片列表
  
  
  
  
  
  
  
  
  
  
  
  
  
    




CY 图片列表

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5079946.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存