图片的保存
从前台jsp页面中上传图片文件到数据库,之后再读取数据库中图片信息进行显示,基于struct2实现,和springmvc中的实现稍稍有点区别。
这里struct2 的URL跳转配置,没有springmvc的注解方便
下面分别是action层的映射和struct中的跳转视图设置,输入URL地址就会由下图的配置跳转到jsp页面去
public String file(){
try {
System.out.println("aAction文件上传跳转设置");
} catch (Exception e) {
e.printStackTrace();
}
return "file";
}
<package name="a" extends="json-default" namespace="/a">
<action name="ab" class="com.fei.action.aAction">
<result name="file">index.jsp</result>
</action>
public Connection getConn(){
//1.getConnection()方法,连接MySQL数据库!!
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","username","password");
//Class.forName("oracle.jdbc.driver.OracleDriver");
//con = DriverManager.getConnection("jdbc:oracle:thin:@//url","username","password");
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
前台jsp页面,一个上传的form和一个超链接,还有一个from输入id值再拿数据库中对应id的图片
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片文件保存与显示</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/a/ab!savefile.action" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="file" width="120px">
<input type="submit" value="提交">
</form>
<br><br>
<!--
<a href="${pageContext.request.contextPath}/a/ab!readerJpg.action">读取bolb保存到E盘</a>-->
<br><br>
<form action="${pageContext.request.contextPath}/a/ab!readerJpg.action" method="post">
<table>
<tr>
<td><label>输入展示的id:</label></td>
<td><input type="text" id="pid" name="pid" /></td>
</tr>
<tr>
<td><input type="submit" id="submit" value="查询图片"></td>
</tr>
</table>
</form>
</body>
</html>
点击提交后会进入seveFile()方法中,保存到save_image表中images(BLOB)字段中,这里的file是IO下的,不支持直接转存到本地磁盘,和本文末尾的springmvc中的保存实现方式有点区别。
struct中接收参数直接在action层定义全局变量,然后直接使用就行。这也是和springmvc在方法入参时定义变量接收有区别。
import java.io.File;
public void savefile(){
try {
Connection con = getConn();
FileInputStream inputStream = new FileInputStream(file);
//String sql="insert into save_image(images,im) values(?,?)";
//存入数据库的SQL语句在执行的时候一定要用prepareStatement
String sql="insert into save_image(images) values(?)";
PreparedStatement prepareStatement = con.prepareStatement(sql);
prepareStatement.setBinaryStream(1, inputStream,(int)file.length());
//prepareStatement.setBinaryStream(2, inputStream,(int)file.length());
prepareStatement.executeUpdate();
inputStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
点击前台jsp页面的查询图片,跳转到这个方法,从数据库中取出数据转化成图片文件保存一份到本地并且输出到前台
public void readerJpg() throws SQLException, ClassNotFoundException{
String JPG="image/jpeg;charset=GB2312";
Connection con = getConn();
String sqlString = "" ;
//sqlString = "select images from save_image where id=6";// 从数据库中读出要还原文件的二进制码,这里我读的是自己的数据库id为6的文件
sqlString = "select images from save_image where id="+pid;
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
File file = new File("E:\\"+ dateFormat.format(new Date())+".jpg");// 本地生成的文件
//将图片文件写入本地磁盘
if (!file.exists()) {
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
byte[] Buffer = new byte[4096 * 5];
PreparedStatement statement = con.prepareStatement(sqlString);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
FileOutputStream outputStream = new FileOutputStream(file);
InputStream iStream = resultSet.getBinaryStream("images");// 相应的字段去用getBinaryStream()
int size = 0;
while ((size = iStream.read(Buffer)) != -1) {
System.out.println(size);
outputStream.write(Buffer, 0, size);
}
outputStream.close();
}
//将图片文件输出到前台页面
// 获取输出流
OutputStream outputStream = response.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(file);
// 读数据
byte[] data = new byte[fileInputStream.available()];
fileInputStream.read(data);
fileInputStream.close();
// 回写
response.setContentType(JPG);
outputStream.write(data);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
对应的数据库建表语句
DROP TABLE IF EXISTS `save_image`;
CREATE TABLE `save_image` (
`id` int(50) NOT NULL AUTO_INCREMENT,
`images` blob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
这里基于springmvc注解实现的保存前台上传的图片到本地磁盘,MultipartFile 可以直接转存到本地路径下。跟上面的代码不相关,放在这里是进行下对比。
@RequestMapping("test")
public String test(@RequestParam("file")MultipartFile file,HttpServletRequest request) throws IOException{
// String path ="D:/workspace2/SpringMVC_02/WebContent/upload";
String path = "D:/workspace2"+request.getContextPath()+"/WebContent/upload";
System.out.println("path>>"+path);
// String fileName = file.getOriginalFilename();
String fileName = "1.jpg" ;
System.out.println("fileName>>"+fileName);
File dir = new File(path,fileName);
System.out.println("dir.exists()>>"+dir.exists());
if(!dir.exists()){
dir.mkdirs();
System.out.println("dir.exists()>>"+dir.exists());
}
file.transferTo(dir);
return "redirect:/list.html";
}