package com.njue.image;
import java.sql.*;
import java.util.ArrayList;
import java.io.*;
import java.nio.*;
public class UploadImage {
String userName="root";
String password="123456";
Connection conn=null;
Statement stmt=null;
String url="jdbc:mysql://localhost:3306/mysql";
public boolean storeImage(String path,String sql) {
try {
File file = new File(path);
//打开文件
FileInputStream fin = new FileInputStream(file);
//建一个缓冲保存数据
ByteBuffer nbf = ByteBuffer.allocate((int) file.length());
byte[] array = new byte[1024];
int offset = 0, length = 0;
//读存数据
while ((length = fin.read(array)) > 0) {
if (length != 1024)
nbf.put(array, 0, length);
else
nbf.put(array);
offset += length;
}
//关闭文件
fin.close();
//新建一个数组保存要写的内容
byte[] content = nbf.array();
//保存数据
return setImage(sql, content);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//如果发生文件读写错误都会返回false
return false;
}
private boolean setImage(String sqlstr, byte[] in) {
boolean flag = false;
if (sqlstr == null)
sqlstr = "select * from image";
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(url,userName,password);
stmt =
conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sqlstr);
if (rs.next()) {
rs.updateBytes(2, in); //2表示更新第二个字段,机image这个字段
rs.updateRow();
} else {
rs.moveToInsertRow();
rs.updateBytes(2, in);
rs.insertRow();
}
rs.close();
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}
JSP往MYSQL中插入,读写图片
4星 · 超过85%的资源 需积分: 50 144 浏览量
2012-03-27
21:19:05
上传
评论 7
收藏 476KB ZIP 举报
pzhtpf
- 粉丝: 1117
- 资源: 19
最新资源
- IMG_20240425_190941.jpg
- 基于stm32的pid控制算法附带串口控制台
- 实验项目一:线性表(模板 ).docx
- 基于LM317A设计交流220V输入可调5V-12V直流输出稳压电源电路multisim10仿真源文件.zip
- Screenshot_2024-04-25-17-04-18-55_2332cb9b27b851b548ba47a91682926c.jpg
- -基于AVR单片机的LNG加液机控制器设计.pdf
- ThePowerOfNow-EckhartTolle.mobi
- BLOCK_TYPE_HEARTBEAT_D70A3465D4EE4E9_046141_dump_1st.dmp
- 项目方法测试调用接口工具
- studyupdate
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
- 1
- 2
- 3
- 4
- 5
- 6
前往页