基於layui框架,實現從jsp頁面上傳圖片到數據庫,熟悉layui框架才能用。
首先如何上傳圖片。

這里為layui 的js 部分和 html
var uploadInst = upload.render({
elem: '#uploadBtn' //上傳按鈕的id
,accept: 'images' // 上傳文件的類型
,auto: false
,size: 1024 * 1024 * 2 //上傳文件的最大 大小 這里為2M
,choose: function(obj){
//預讀本地文件示例,不支持ie8
//當用戶點擊上傳並選好圖片之后,將圖片轉為base64格式
obj.preview(function(index, file, result){
//直接將img的src屬性值 轉為base64 立即顯示在右側
$('#faceImg').attr('src', result); //圖片鏈接(base64)
//將隱藏域中的值改為base64傳給后台
$(":hidden[name=face]").val(result);
});
}
; })
<label class="layui-form-label">頭像</label>
<div class="layui-input-block">
<div class="layui-inline">
<img style="border-radius:10%; width:200px;height:200px;" onerror="this.src='${ctx}/images/default.jpg'" src="${ctx}/user.do?method=initFace&face=${dbUser.face}" class="layui-upload-img" id="faceImg">
</div>
<div>
<button style="margin-left: 150px" type="button" class="layui-btn" id="uploadBtn">上傳頭像</button>
</div>
當用戶點擊提交后,會將生成的base64代碼,通過隱藏域上傳后Controller層中,然后再調用pojo類,用User對象的setFace 方法將base64存儲起來。
這時候在跳轉到service中,調用如下方法處理base64
private String uploadFace(String face) {
//獲取到base64中,圖片的后綴
int index1 = face.indexOf("/") + 1;
int index2 = face.indexOf(";");
String hz = face.substring(index1, index2);
//拼接好,圖片的名稱
String fileName = "d:/fileUpdate/" + UUID.randomUUID().toString() + "." + hz;
BASE64Decoder decoder = new BASE64Decoder();
OutputStream os = null;
try {
//截取base64中的正文主體部分
byte[] bytes = decoder.decodeBuffer(face.substring(face.indexOf(",") + 1));
File file = new File(fileName);
//這里會通過fileName,在對應的路徑中創建這個圖片
file.createNewFile();
os = new FileOutputStream(file);
os.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//將fileName返回出去。然后存儲在數據庫中
return fileName;
}
到這里就將圖片上傳做好了,接下來就是讀取圖片
onerror="this.src='${ctx}/images/default.jpg'" src="${ctx}/user.do?method=initFace&face=${dbUser.face}"
上面這段代碼為img 的屬性, onerror 為當src找不到對應路徑時顯示的圖片。即默認初始化的頭像
當頁面加載時,會通過src 去訪問servlet。 將當前登陸對象的face屬性(face為圖片路徑)傳到servlet中。然后調用initFace方法通過路徑顯示圖片
private void initFace(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
//url傳值中獲取到頭像的路徑
String facePath = request.getParameter("face");
//路徑
File file = new File(facePath);
if(!file.exists()){
return;
}
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(file);
os = response.getOutputStream();
byte[] b = new byte[1024*10];
// 正常返回讀到的數據個數, 沒有了就返回-1
int len = 0;
while((len = is.read(b))!=-1){
os.write(b,0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
