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.mzph.cn/news/541054.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ITU衡量信息社会报告:我国ICT发展指数进入亚太前十

11月22日&#xff0c;国际电信联盟&#xff08;ITU&#xff09;发布2016版《衡量信息社会报告》&#xff0c;公布了最新国家和地区ICT发展指数&#xff08;IDI&#xff09;。《报告》显示&#xff0c;排在前十位的国家和地区均来自欧洲和亚洲&#xff0c;韩国以0.01分的优势再次…

treeset java_Java TreeSet clear()方法与示例

treeset javaTreeSet类的clear()方法 (TreeSet Class clear() method) clear() method is available in java.util package. clear()方法在java.util包中可用。 clear() method is used to clear all of the objects that exist from this TreeSet. clear()方法用于清除此TreeS…

Facebook也大干新闻聚合 “新闻快读”向所有媒体开放

去年五月&#xff0c;Facebook推出了不离开本站直接阅读新闻的聚合服务“新闻快读”&#xff08;Instant Articles&#xff09;&#xff0c;用户载入文章的速度大增&#xff0c;不过当时只面向一些特定合作的新闻机构。日前&#xff0c;这一聚合服务全面开始接纳所有的新闻媒体…

kafka偏移量保存到mysql里_【队列】调试应用时进行的kafka偏移量调整

# KAFKA操作记录##export BASE_DIR/home/dba/kafkaexport SERVERS1.1.1.1:9092cd ${BASE_DIR}/bin# 删除残留的消费者./kafka-consumer-groups.sh --bootstrap-server $SERVERS --group DBAAlertSplash --delete --command-config ${BASE_DIR}/config/client.properties# 这个在…

java scanner_Java Scanner match()方法与示例

java scanner扫描器类match()方法 (Scanner Class match() method) match() method is available in java.util package. match()方法在java.util包中可用。 match() method is used to get the MatchResult of the last scanning operation operated by this Scanner. match()…

苹果再次拒绝协助美国政府解锁纽约毒品案中的iPhone

继美国联邦调查局(FBI)成功解锁圣贝纳迪诺市恐袭案枪手 Syed Farook所使用的iPhone 5c后&#xff0c;美国司法部已撤回对苹果公司采取的法律行动。然而近日美国司法部宣布&#xff0c;将继续要求苹果公司协助解锁一部在纽约毒品调查案中查获的iPhone 5s手机。不过苹果今天向美国…

openssl java aes_请问如何使用AES对使用OpenSSL命令加密的Java文件进行解密?

以下是OpenSSLPBEInputStream和OpenSSLPBEOutputStream它可以用于以与OpenSSL兼容的方式加密/解密任意字节流。示例用法&#xff1a;// The original clear text bytesbyte[] originalBytes ...// Encrypt these byteschar[] pwd "thePassword".toCharArray();Byte…

Java ArrayList set()方法与示例

ArrayList类set()方法 (ArrayList Class set() method) set() method is available in java.util package. set()方法在java.util包中可用。 set() method is used to replace the element at the given indices with the given ele(element) in this Arraylist. set()方法用于…

《R的极客理想—工具篇》—— 第2章 时间序列基础包

本节书摘来自华章出版社《R的极客理想—工具篇》一 书中的第2章&#xff0c;作者&#xff1a;张丹&#xff0c;更多章节内容可以访问云栖社区“华章计算机”公众号查看。 第2章 时间序列基础包 本章主要介绍了时间序列数据处理的3个工具包&#xff0c;帮助读者掌握时间序列在R语…

java结构设计_Java基本的程序设计结构(一)

前言&#xff1a;虽然说学过设计模式&#xff0c;J2EE&#xff0c;这个学期才开始学Java&#xff0c;呵呵&#xff0c;有点颠倒了&#xff0c;但是还是要从基本的抓起。hoho&#xff5e;&#xff5e;(一)一个简单的java应用程序Package edu.ynu.java.lession1/*The simplest Ja…

Java ArrayList get()方法与示例

ArrayList类的get()方法 (ArrayList Class get() method) get() method is available in java.util package. get()方法在java.util包中可用。 get() method is used to retrieve the element at the given index in this Arraylist. get()方法用于检索此Arraylist中给定索引处…

第三方应用商店仍为用户获取APP主渠道 细分市场或成新增长点

近年来&#xff0c;在应用分发市场领域随着渠道多元化趋势日渐显现&#xff0c;第三方应用商店似乎已经显得乏善可陈&#xff0c;缺少亮点。事实上&#xff0c;根据比达咨询(Big Data-Research)发布的《2016年第一季度中国第三方应用商店市场研究报告》显示&#xff0c;第三方应…

java反射 动态调用_java反射拼接方法名动态执行方法

近期由于负责项目的一个模块,该模块下有很多分类,每个分类都有一个编码code,这个值是作为一个参数携带过来的.但是每个code确实对应一个方法的.code的值有很多个,自己又不想做ifelse或者switch判断于是就狂搜资料,主要让我发现利用java的反射机制可以完美的解决这个问题测试代码…

Python | Lambda函数与示例

With the help of lambda function, we can create one line function definition. 借助lambda函数&#xff0c;我们可以创建一个行函数定义。 Note: Function must have return type and parameter 注意&#xff1a;函数必须具有返回类型和参数 Example: 例&#xff1a; Co…

使用大数据闪存打造融合数据平台

随着企业、服务提供商和超大型数据中心从描述性分析向预测性和规范性分析演进&#xff0c;结合了融合运营和分析数据管道的融合数据平台变得日益重要。大数据闪存可让数据处理平台快速访问历史数据和实时数据流&#xff0c;从而以较低成本创建有效的预测模型。 随着大数据从描述…

stl min函数_std :: min()函数以及C ++ STL中的示例

stl min函数C STL std :: min()函数 (C STL std::min() function) min() function is a library function of algorithm header, it is used to find the smallest value from given two values, it accepts two values and returns the smallest value and if both the value…

c# uri.host_C#| Uri.FromHex()方法与示例

c# uri.hostUri.FromHex()方法 (Uri.FromHex() Method) Uri.FromHex() method is a static method that returns an integer that represents a decimal digit of specified hex char. Uri.FromHex()方法是一个静态方法&#xff0c;该方法返回一个整数&#xff0c;该整数表示指…

中国制造2025变革,背后的大数据来龙去脉

大数据的成长路径一定是个长期成长过程&#xff0c;实用分析工具与先进分析理念&#xff0c;真正释放数字化分析的力量&#xff0c;由人类轨迹产生的数据&#xff0c;与机器自动产生的数据得出洞见&#xff0c;从管理决策推导运营方案&#xff0c;最终实现数据价值提升。无论是…

java 文件下载 jsp文件_jsp文件 Java实现文件上传与下载

通过前台选择文件&#xff0c;然后将资源上传到(即新建一个文件)到发布的资源文件下面&#xff0c;下载就是url 到发布的资源文件&#xff0c;触发即可自动下载。服务器已经封装了如何下载的底层实现。(此处用的是tomcat)JSP上传文件方法&#xff1a;关于在HTTP request 中通过…

ruby hash方法_Ruby中带有示例的Hash.flatten方法

ruby hash方法哈希平化方法 (Hash.flatten Method) In this article, we will study about Hash.flatten Method. The working of this method can be predicted with the help of its name but it is not as simple as it seems. Well, we will understand this method with t…