zoukankan      html  css  js  c++  java
  • web项目从数据库中的图片上传和读取

    (不建议使用,会影响项目的运行速度)

    前言:

    现在的web项目是都是有图片的,而企业级的都有专门的存储服务器,但是对于个人使用,我目前知道的就有两种

    第一种是文件数据不在数据库,而是在项目中建立一个文件夹,文件的上传和读取都是在该文件夹下存取,只有文件名存储到数据库,这种有一个缺点,我的数据当吧生成的war包删除以后就有无法找到上传的文件数据了,需要重新上传;

    第二种是把图片存储到数据库中,以二进制的方式存储到数据库,然后读取的时候再读取

    我更偏向于第二种,具体的操作如下:

    *我的是springboot项目:

    数据库的表:

    javabean:

    public class Image {
        private Integer id;
    
        private String imageName;
    
        private String imageUrl;
    
        private byte[] imageContent;
    //get和set方法自己添加,这里只为说明要义 }

    controller层:

    @RequestMapping("/imageupload")
    @ResponseBody
    public Object searchMember(MultipartFile file){
        try {
            InputStream ins = file.getInputStream();
            byte[] buffer=new byte[1024];
            int len=0;
            ByteArrayOutputStream bos=new ByteArrayOutputStream();
            while((len=ins.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            bos.flush();
            byte data[] = bos.toByteArray();
    
            Image image =new Image();
            image.setImageContent(data);
            image.setImageName("test");
            image.setImageUrl("/testimage");
            int result = imageService.insert(image);
            return "ok"+result;
    /*       Student s=new Student();
           s.setId(sId);
           s.setPhoto(data);
           studentService.insertPhoto(s);*/
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "ok";
    
    }
    
        /**
         * 从数据库到页面显示图片
         * @return
         */
        @RequestMapping(value = "/showimage",produces = MediaType.IMAGE_JPEG_VALUE)
        @ResponseBody
        public byte[] toImageShow(){
    //这里是从数据库读取图片,你可以根据自己的业务读取你的数据 Image image
    =imageService.selectByPrimaryKey(1); return image.getImageContent(); }

    上传的页面:

    <form action="/imageupload" method="post" enctype ="multipart/form-data">
        <label for="file" class="btn btn-primary" style="float: left;height: 30px; 180px;margin-right: 20px">点击选择考生照片</label>
        <input  id="file" name="file" type="file" style="float: left;display:none"/>
        <input  class="btn btn-primary" type="submit" value="提交" style="float: left">
    </form>

    显示的页面:

    <img src="/showimage" alt="失败" />

    最后感谢一下以下博客:

    https://blog.csdn.net/u014449560/article/details/82807517

    https://www.cnblogs.com/xiaowangxiao/p/10936537.html

  • 相关阅读:
    lxml webdriver 抓取街拍
    python 正则抓取古诗词
    2021 最新版 Spring Boot 速记教程
    hbase 命令查看表大小
    Spring AOP,应该不会有比这更详细的介绍了!
    SpringBoot实战:整合Redis、mybatis,封装RedisUtils工具类等
    API接口的安全设计验证:ticket,签名,时间戳
    5.控制台输出空心菱形
    4.灯泡开关问题
    EXCEL函数
  • 原文地址:https://www.cnblogs.com/Anxc/p/12462549.html
Copyright © 2011-2022 走看看