上传文件与表格照片
开发工具与关键技术:MyEclipse 10、java
作者:梁添荣
撰写时间:2019-6-08
有时项目需求,需要上传文件到数据库,查询出来的表格里有照片,此时需要准备两个jra包:comons-fileupload.jar和commons-io.jar
jsp from表单加属性enctype="multipart/form-data"
以下为上传文件:
private void insertImg(HttpServletRequest request,
HttpServletResponse response) {
//创建静态工厂
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload fileUpload=new ServletFileUpload(factory);
//upload.setFileSizeMax(1024*400);设置上传的文件
//upload.setHeaderEncoding("gbk");
List<FileItem> items=null;
try {
items=fileUpload.parseRequest(request);//执行一遍fileUpload.parseRequest(request)后该语句内容就会变成null
} catch (FileUploadException e) {
e.printStackTrace();
}
for (FileItem fileItem : items) {
if(fileItem.isFormField()){
String fileName=fileItem.getFieldName();
String value=fileItem.getString();
System.out.println(fileName+"的值是"+value);
}else{
try {
// String folder = System.getProperty("user.dir");??
//写入服务器
byte[] b=new byte[10240*10];
InputStream inputStream= fileItem.getInputStream();
inputStream.read(b);//写进byte
String path=this.getServletContext().getRealPath("/photo/P1112.PNG");
File file=new File(path);
FileOutputStream out=new FileOutputStream(file);
out.write(b,0,b.length);
out.flush();
out.close();
try {
//图片写入数据库
Class.forName(driver);
Connection connection=DriverManager.getConnection(url,username,password);
PreparedStatement ps=connection.prepareStatement(insert);
ps.setString(1, "试试");
//如果 inputStream.read(b);//写进b了
ps.setBytes(2, b);//就用这个增进数据库
//如果没有inputStream.read(b); 直接把字节流写进
// ps.setBinaryStream(2, inputStream);
ps.executeUpdate();
connection.close();
ps.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//表格照片
//查询照片
private final ReentrantLock lock = new ReentrantLock();
@Override
public void photo(HttpServletRequest request, HttpServletResponse response,
int id) {
lock.lock();
try {
con=DBUtil.connection();
ps=con.prepareStatement(photo);
ps.setInt(1, id);
rs=ps.executeQuery();
while(rs.next()){
InputStream in=rs.getBinaryStream("Photo");
OutputStream ou=response.getOutputStream();
byte[] b=new byte[1024*10];
int n;
while((n=in.read(b))!=-1){
ou.write(b,0,n);
}
ou.flush();
ou.close();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
DBUtil.colse(con, ps, rs);
lock.unlock();
}
}
Jsp代码
<c:forEach items="${drivers }" var="driver">
<tr>
<td style="display: none;">${driver.driverID }</td>
<td>${driver.drivernumber }</td>
<td>${driver.driverName }</td>
<td>${driver.sex==false?"男":"女" }</td>
<td>${driver.phone }</td>
<td>${driver.iDno }</td>
<td>${driver.quasidrivingtype }</td>
<td><img src="servlet/Servlet?type=photo&id=${driver.driverID }" width="50px" height="60px" /></td>
</tr>
</c:forEach>