zoukankan      html  css  js  c++  java
  • javaweb上传图片存到本地,并存储地址到数据库

    前端使用layui的图片上传,将文件base64编码,然后在后端使用转码类来操作base64编码,并保存图片到本地,继而获取文件地址,将文件地址保存到数据库中

    1.使用layui的图片上传

    infoset.jsp
    layui.use('upload', function() {
        var $ = layui.jquery;
        var upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1',
            //根据id上传图片
            url: 'http://localhost:8080/user?method=updateUserPhoto&id='+id, //改成您自己的上传接口
            method: 'post' , //可选项。HTTP类型,默认post
            auto: false, //选择文件后不自动上传
            bindAction: '#ListAction' ,//指向一个按钮触发上传
            choose: function(obj){
                //将每次选择的文件追加到文件队列
                var files = obj.pushFile();
                //预读本地文件,如果是多文件,则会遍历。(不支持ie8/9)
                obj.preview(function(index, file, result) {
                    console.log(index); //得到文件索引
                    console.log(file); //得到文件对象
                    console.log(result); //得到文件base64编码,比如图片
                    $('#demo1').attr('src', result); //图片链接(base64)
                    $.post("http://localhost:8080/user?method=updatePhoto", {result:result,id:id}, function(res) {
                        console.log("updatePhoto请求成功");
                    }, "text");//这里用的是post提交,如果不懂可以参考JQuery中ajax提
                })
            },
            done: function(res) {
                //如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                //上传成功
            },
            error: function() {
                //演示失败状态,并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #c158ff;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function() {
                    uploadInst.upload();
                });
            }
        });
    });
    

    2.后端使用编码类转码,保存图片到本地

    UserServlet
    String basedata=req.getParameter("result");
    Integer useridtwo = Integer.parseInt(req.getParameter("id"));
    System.out.println("UserServlet中使用方法updatePhoto获取数据为:" + basedata);
    String position=PhotoUtils.GenerateImage(basedata,"reader");
    //通过id存储地址
    Reader readertwo = userService.findUserById(useridtwo);
    //传递两个参数去取代返回值为是否成功保存地址
    if (userService.updatePhoto(readertwo,position) == 1) {
        System.out.println("updatePhoto数据更新成功");
    }
    
    PhotoUtils
    import org.apache.commons.fileupload.FileItem;
    import sun.misc.BASE64Decoder;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.util.Date;
    
    public class PhotoUtils {
        //base64字符串转化成图片
        public static String GenerateImage(String imgStr,String wenjian)
        {
            System.out.print("已经收到了把字节码转化为图片的方法");
            //对字节数组字符串进行Base64解码并生成图片
            if (imgStr == null) //图像数据为空
                return "error";
    
            //解析base64码,获取图片格式
            String str [] = imgStr.split(",");
            imgStr = str[1];
            String imgInfo = str[0];
            String imgExt = imgInfo.split("/")[1].split(";")[0];
    //        String imgExt="gif";
    
            BASE64Decoder decoder = new BASE64Decoder();
            try
            {
                //Base64解码
                byte[] b = decoder.decodeBuffer(imgStr);
                for(int i=0;i<b.length;++i)
                {
                    if(b[i]<0)
                    {//调整异常数据
                        b[i]+=256;
                    }
                }
                String imgFileReturn= "http://localhost:8080/image/"+getPhotoNewName(imgExt,wenjian);
                String imgFilePath = "E:\JavaProject\bookManage\web\image\"+"\"+getPhotoNewName(imgExt,wenjian);//新生成的图片
    //            String imgFilePath = "E:\image\"+"\"+getPhotoNewName(imgExt,wenjian);//新生成的图片
                System.out.println(imgFilePath);
                OutputStream out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
                return imgFileReturn;
            }
            catch (Exception e)
            {
                return "";
            }
        }
        /**
         *这个函数的功能是获取当前时间点与1970年的间隔秒数
         */
        public static int getSecondTimestamp(Date date){
            if (null == date) {
                return 0;
            }
            String timestamp = String.valueOf(date.getTime());
            System.out.println(timestamp);
            int length = timestamp.length();
            if (length > 3) {
                return Integer.valueOf(timestamp.substring(0,length-3));
            } else {
                return 0;
            }
        }
    
        /**
         *
         *这个函数的功能是得到新的照片名称
         */
        public static String getPhotoNewName(String imgExt,String wenjian) {
            Date date=new Date();
            int second=getSecondTimestamp(date);
            String fileName=wenjian+String.valueOf(second)+"."+imgExt;
            return fileName;
        }
    }
    
    ReaderRepositoryImpl
    @Override
    public Reader findUserById(int id) {
        //之前定义的包装类用于c3p0连接池的使用
        Connection connection = JdbcTools.getConnection();
        String sql = "select * from reader where id=?";
        //执行sql语句
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        Reader reader = null;
    
        try {
            statement = connection.prepareStatement(sql);
            //参数代替问号
            statement.setInt(1,id);
            resultSet = statement.executeQuery();
            if (resultSet.next()) {
                //单个数据的替代,
                reader = new Reader(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getString(4), resultSet.getString(5), resultSet.getString(6), resultSet.getString(7), resultSet.getInt(8), resultSet.getString(10));
            }
    
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcTools.release(connection, statement, resultSet);
        }
        return reader;
    }
    
  • 相关阅读:
    1scala基础
    3scala高级
    03spark kafka
    01spark基础
    04spark streaming
    2scala集合
    02spark sql
    学习java程序设计环境的心得
    第五章继承
    第二周学习Java心得
  • 原文地址:https://www.cnblogs.com/dongxuelove/p/14032261.html
Copyright © 2011-2022 走看看