1. 程式人生 > 實用技巧 >javaweb上傳圖片存到本地,並存儲地址到資料庫

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