java mysql 存儲圖片_Java存儲圖片到Mysql

該樓層疑似違規已被系統折疊?隱藏此樓查看此樓

【1】視圖層

action="${ctx}/web/UserInforServlet?method=userInforServlet" >

p><p>

更換頭像

立即提交

重置

var layer,upload,form;

//1-頁面數據加載

$(function () {

//【1】加載&初始化layui模塊-彈出層與table數據表格

layui.use(["layer", "upload","form"], function () {

layer = layui.layer;

laydate=layui.laydate;

upload = layui.upload;//layui的上傳

form= layui.form;

uploadImage();

});

});

function uploadImage(){

var $ = layui.jquery;

upload.render({

elem: "#upImage"

,auto: false

,size:1024

,choose: function(obj){//使用choose選擇文件后的回調函數

//預讀本地文件示例,不支持ie8

obj.preview(function(index, file, result){

$("#userImge").attr("src",result); //圖片鏈接(base64)

});

}

});

}

//提交form表單

$("#saveUserInfor").click(function(){

$("#frregister").ajaxSubmit(function(data) {

if(data="1"){

layer.msg("成功!");

}

});

});

【2】控制器

publicvoid userInforServlet(HttpServletRequest request,HttpServletResponseresponse) throws IOException {

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=UTF-8");//處理響應編碼

Map map=new HashMap();

UserDetail userDetail=new UserDetail();

try {

//【1】解析數據

DiskFileItemFactory fac=new DiskFileItemFactory();

int sizeThreshold=1024*1024*10; //10MB

fac.setSizeThreshold(sizeThreshold);

fac.setRepository(new File(System.getProperty("java.io.tmpdir")));

ServletFileUpload upload=new ServletFileUpload(fac);//文件上傳解析器

upload.setHeaderEncoding("utf-8");

Listlist=upload.parseRequest(request);

//【2】遍歷集合

for(FileItem item :list){

//1)如果當前FileItem對象是普通項

if(item.isFormField()){

map.put(item.getFieldName(),item.getString());

}else{

//1)如果當前FileItem對象是上傳項

//2)判斷是否存在有該文件夾

String realPath=("D:/Mytouimage");

File uploadMkdir=new File(realPath);

if(!uploadMkdir.exists()){

uploadMkdir.mkdir();

}

//如果fileitem中封裝的是上傳文件,得到上傳的文件名稱,

String fileName = item.getName();//上傳文件的名

//多個文件上傳時,沒有上傳內容的問題異常處理

if(fileName==null||"".equals(fileName.trim())){ continue;

}

fileName =fileName.substring(fileName.lastIndexOf("\\")+1);

InputStream is=item.getInputStream();

File file=new File(realPath+"/"+fileName);

//3)先在本地存儲圖片,再讀取保存到數據庫

if(!file.isDirectory()){

userDetail.setImageName(realPath+"/"+item.getName());

OutputStream os=new FileOutputStream(file);

//IOUtils拷貝流

IOUtils.copy(is,os);

//關閉資源

IOUtils.closeQuietly(is);

IOUtils.closeQuietly(os);

item.delete();//刪除處理文件上傳時生成的臨時文件

}

}

}

BeanUtils.populate(userDetail,map);

int flag =ids.insert(userDetail);

if(flag==1){

response.getWriter().write("1");

response.getWriter().close();

}

}

【3】dao層

@Override

publicint insert(UserDetail t) {

int flag=0;

InputStream fis=null;

String insert="INSERT INTOr_userdetail(userImage,imageName)" +

"VALUES(?,?);";

try {

con=JDBCUtil.getConnection();

ps=con.prepareStatement(insert);

if(t.getImageName()!=null){

//讀取本地圖片

fis=new FileInputStream(t.getImageName());

}

//將流寫入Mysql

ps.setBinaryStream(1, fis, fis.available());

ps.setString(2, t.getImageName());

flag=ps.executeUpdate();

} catch (SQLException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

catch (FileNotFoundException e){

//TODO Auto-generated catch block

e.printStackTrace();

}

catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

return flag;

}

【4】po層

publicclass UserDetail implements Serializable{

publicstaticfinallongserialVersionUID = 42L;

privateintuserDetailID;

private Blob userImage;

private String imageName;

public Blob getUserImage() {

returnuserImage;

}

publicvoid setUserImage(Blob userImage) {

this.userImage = userImage;

}

public String getImageName() {

returnimageName;

}

publicvoid setImageName(String imageName) {

this.imageName = imageName;

}

}

【5】總結

1)注意上傳圖片是form表單一定要加method="post" enctype="multipart/form-data" ,否則無法將數據上傳到服務器。

2)Mysql存儲圖片的數據類型

TinyBlob最大 255

Blob 最大 65K

MediumBlob 最大 16M

LongBlob 最大 4G

3)在dao層向數據庫添加數據

使用ps.setBinaryStream(1,fis, fis.available());

【6】顯示圖片

publicvoid selectUserImage(HttpServletRequest request, HttpServletResponseresponse) {

String id=request.getParameter("userID");

if(id!=null){

int userID=Integer.parseInt(id);

UserDetail userDetail=ids.findByUserid(userID);

BufferedOutputStream bufos=null;

BufferedInputStream bufis=null;;

try {

if(userDetail.getUserImage()!=null){

//讀取緩沖區 userDetail.getUserImage().getBinaryStream()--讀取源

bufis=new BufferedInputStream(userDetail.getUserImage().getBinaryStream());

//輸出緩沖區 response.getOutputStream()--輸出目的

bufos = new BufferedOutputStream(response.getOutputStream());

byte[] bt=newbyte[1024];

//【6】初始化實際長度的數組的長度

int count=0;

//【7】循環讀取多媒體文件數據,將其讀取的數據存儲在byte數組

while((count=bufis.read(bt))!=-1){

//【8】截取數組從零到實際長度,循環寫入多媒體的目標文件

bufos.write(bt,0,count);

}

}

bufis.close();

bufos.close();

} catch (SQLException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

catch (IOException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/540000.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/540000.shtml
英文地址,請注明出處:http://en.pswp.cn/news/540000.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

JavaWeb應用配置文件安全解決方案

這里主要說說JavaWeb應用的配置文件安全&#xff0c;通常JavaWeb應用多多少少會有一些配置文件&#xff0c;其中數據源的配置則是關系到數據庫的安全&#xff0c;另外還有一些基于文件的權限配置&#xff0c;應用程序的一些系統參數。鑒于這樣的情況&#xff0c;如果配置文件被…

java 免費cms_開源 免費 java CMS

Bug修復:1.菜單管理&#xff1a;刪除操作按鈕后不能直接進行刪除菜單操作。2.刪除單位時操作記錄不顯示單位名稱問題。3.站點管理&#xff1a;改變所屬站點增加改變為一級站點功能&#xff0c;上傳非圖片logo時雖然提示但仍上傳成功問題。4.模板文件管理&#xff1a;點擊查看/下…

Android加載大圖片不OutOfMemoryError

Android加載圖片時&#xff0c;對于分辨率小&#xff0c;配置低的機子&#xff0c;很容易發生OutOfMemoryError。手機的內存比圖片的大很多&#xff0c;怎么會這樣&#xff1f; 在設置Android虛擬機的內存時&#xff1a; RAM&#xff1a;模擬器的內存空間 VM Heap&#xff1a;…

任務計劃、chkconfig工具、systemd管理服務、unit、target

比如備份數據或者重啟服務。 crontab -u、-e、-l、-r&#xff08;刪除&#xff09; 格式&#xff1a;分 時 日 月 周 user command 文件/var/spool/cron/username 分范圍0-59&#xff0c;時范圍0-23&#xff0c;日范圍1-31&#xff0c;月范圍1-12&#xff0c;周1-7 可用格式1-5…

vue打卡日歷_Vue日歷

new Vue({el: ‘#calendar‘,data: {currentDay: 1,currentMonth: 1,currentYear: 1970,currentWeek: 1,days: [],addDay: [],},created: function() {this.initData(null);var $this this;//請求數據$.ajax({url: "這里填接口名稱",type: "POST",data: {…

android Intent機制詳解

原文出處&#xff1a;http://blog.csdn.net/t12x3456/article/details/7688154 什么是Intent Intent是一種運行時綁定&#xff08;run-time binding&#xff09;機制&#xff0c;它能在程序運行過程中連接兩個不同的組件。通過Intent&#xff0c;你的程序可以向Android表達某種…

python基本數據類型(四)-集合與運算符-python3筆記

1.集合 2.字典 3.運算符優先級 1.集合 創建&#xff1a;() set() 注意&#xff1a;創建空的集合要用set() 特點&#xff1a;元素唯一&#xff0c;無序 運算&#xff1a; &&#xff08;交集&#xff09; |&#xff08;并集&#xff09; -&#xff08;差集&#xff0…

Android的權限

Android有四種權限&#xff1a; 1、Permission 權限 2、Root權限 3、Bootloader的解鎖 4、Radio(基帶)解鎖 ------------------------------------ 1、Permission 我們在開發中經常使用到 Permission 權限&#xff0c;即一系列"Android.Permission.*"對象。…

hive2 java連接_用Java代碼通過JDBC連接Hiveserver2

1.在終端啟動hiveserver2#hiveserver22.使用beeline連接hive另外打開一個終端&#xff0c;輸入如下命令(xavierdb必須是已經存在的數據庫)#beeline -u jdbc:hive2://localhost:10000/xavierdb -n hive -p hive3.添加maven依賴org.apache.hivehive-jdbc1.1.0junitjunit4.9org.ap…

java 向上拋異常_Java 異常的處理方式throws

在昨天的文章《Java 異常的分類與處理》中我們簡單地了解了一下在方法聲明的位置上使用throws關鍵字向上拋出異常&#xff0c;下面深入講解異常的第一種處理方式throws。下面深入講解異常的第一種處理方式throws。看以下例子&#xff1a;import java.io.*;public class Excepti…

Jquery mobile 解決IOS9selectli閃退問題

升級IOS9后&#xff0c;JQuery mobile 出現了個bug問題。<select>&#xff0c;<ul><li></li></ul> 出現閃退。 解決方法&#xff1a; 必須加在 jquery.js 和 jquerymobile.js 中間 <script src"......../...../jquery-2.0.0.min.js&qu…

JAVA通過SSL證書創建MS AD賬戶及設置密碼

近期由于工作需要整理一下自動化的東西&#xff0c;因為公司去年上線了OA&#xff0c;所以公司的入職系統會提交用戶的信息到IT部門&#xff0c;最早的做法是入職到了&#xff0c;IT部門收集用戶信息在AD中創建對應的用戶信息&#xff0c;所以為了提高管理員的工作效率&#xf…

java 實體類規范_實體類的規范

1.Boolean類型1.1.使用Boolean類型,而不是Byte類型1.2.數據庫字段名使用is_開頭1.3.實體類字段名不使用is開頭例子/*** 是否為新消息*/Column(name "is_new_message", nullable false)private Boolean newMessage;2.Enum類型1.使用Convert注解, 并指定coverter類例…

01電話撥號器

實例非常簡單&#xff0c;意在體驗Android的Intent&#xff0c;用戶權限。 Intent 見 http://blog.csdn.net/zengmingen/article/details/49586045 用戶權限 見 http://blog.csdn.net/zengmingen/article/details/49586569 --------------------------------------------------…

微信小程序筆記六模塊化 —— module.exports

微信小程序中所有 js 文件作用域皆為獨立的&#xff0c;每一個 js 文件即為一個模塊。模塊與模塊之間的引用通過 module.exports 或 exports 對外暴露接口。 注意&#xff1a; exports 是 module.exports 的一個引用&#xff0c;因此在模塊里邊隨意更改 exports 的指向會造成未…

java常用的統計_(OJ)Java常用類-統計數字次數

統計數字次數Problem Description命令行輸入一個由數字組成的任意字符串,統計出每個數字出現的次數。Input Description1239586838Output Description0 counts:01 counts:12 counts:13 counts:24 counts:05 counts:16 counts:17 counts:08 counts:39 counts:1解題代碼import ja…

02發送短信

使用SmsManager發送短信java.lang.Object ?android.telephony.SmsManagerManages SMS operations such as sending data, text, and pdu SMS messages. Get this object by calling the static method SmsManager.getDefault().管理短信操作&#xff0c;如發送數據&#xff…

Python運行環境與異常處理

Python的命令格式&#xff1a; python [option] ... [-c cmd | -m mod | file | -] [arg] ... 選項描述-J 啟動將從Python3中刪除或更改某些功能的警告 -B阻止在導入時創建.pyc或.pyo文件-E忽略環境變量-h打印所有可用命令行選項的列表-i在程序執行后進入交互模式-m module以腳…

Java應用一般架構

原文鏈接&#xff1a;http://www.iteye.com/news/31115 當我們架設一個系統的時候通常需要考慮到如何與其他系統交互&#xff0c;所以我們首先需要知道各種系統之間是如何交互的&#xff0c;使用何種技術實現。 1. 不同系統不同語言之間的交互 現在我們常見的不同系統不同語…

Mac MongoDB未正常關閉導致重啟失敗

你可以刪除掉mongod.lock文件&#xff0c;然后重新啟動&#xff0c;如果還是不可以&#xff0c;你可以查看一下進程&#xff0c;然后殺掉&#xff1a; ps -aef | grep mongo sudo kill 1076 再重啟數據庫即可。