大家,谁那里有java的上传图片的代码吗?
是把图片先转换成二进制,存放在数据库里面,用的是mysql数据库,
让后在其他页面 通过从数据库中读出二进制 再转换为图片 在页面显示出来. 如下是把图片转换成二进制中的 action方法如下:
public ActionForward doLoad(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LazyValidatorForm imageForm = (LazyValidatorForm) form;// TODO
// Auto-generated
// method stub FormFile file = (FormFile) imageForm.get("img");
int i = 0;
try {
byte[] img = file.getFileData(); Image imgEntity = new Image();
imgEntity.setImgId(new Integer(31));
imgEntity.setImageContent(img);
imgBiz.addImage(imgEntity);
i = 1;
if (i > 0) {
request.setAttribute("i", "i等于1,执行");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return mapping.findForward("success");
} 就差如何 显示所有的图片.
是把图片先转换成二进制,存放在数据库里面,用的是mysql数据库,
让后在其他页面 通过从数据库中读出二进制 再转换为图片 在页面显示出来. 如下是把图片转换成二进制中的 action方法如下:
public ActionForward doLoad(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
LazyValidatorForm imageForm = (LazyValidatorForm) form;// TODO
// Auto-generated
// method stub FormFile file = (FormFile) imageForm.get("img");
int i = 0;
try {
byte[] img = file.getFileData(); Image imgEntity = new Image();
imgEntity.setImgId(new Integer(31));
imgEntity.setImageContent(img);
imgBiz.addImage(imgEntity);
i = 1;
if (i > 0) {
request.setAttribute("i", "i等于1,执行");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return mapping.findForward("success");
} 就差如何 显示所有的图片.
BufferedImage bi = ImageIO.read(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "jpg", baos);
byte[] bytes1 = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 =ImageIO.read(bais);
File w2 = new File("C:/22.jpg");
ImageIO.write(bi1, "jpg", w2);
InputStream in = null;
try
{
String sql="取你的记录";
ResultSet rs =stmt.executeQuery(sql);
if(rs.next())
{
in = rs.getBinaryStream("xxx");
byte[] buf = new byte[1024];
while ((len=in.read(buf,0,1024))!=-1)
{
out.write(buf, 0, len);
}大体步骤就是上面的,读出2进制,写出来就行了。
但是,我建立将上传的文件保存到服务器某个目录,而数据库中存放的是路径。显示的时候直接读取路径显示就行了。