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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM