java:servlet接收图片,并把它保存到数据库中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java:servlet接收图片,并把它保存到数据库中相关的知识,希望对你有一定的参考价值。

我要做的就是把传过来的图片保存到数据库中。图片是以流的方式传过来的。我怎么对流进行解析,把图片的各属性,比如大小,名称,类型保存到表的各个字段中。如果保存成功,就进行刷新;失败,就alert提示。今天一天时间,希望大神可以做出来。

这种代码网上不是一大片吗

public boolean storeImage(File file)
        try
            // 打开文件
            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();
            String sql = "insert into images (bin_data) values (?) ";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setBytes(1,content);
            pstmt.execute();
            pstmt.close();
        catch(Exception e)
            e.printStackTrace();
            return false;
        
        return true;
    

追问

还是看不太懂啊,麻烦在说一下啊。图片以流的方式传到servlet中以后,我要对它解析。把它的名称,类型都一一解析出来,再进行保存。保存我会,就是不知道怎么解析啊。

追答


common-io.jar
common-upload.jar

封装好了

追问

说的太深奥了啊。那好吧,我再问一下,一个图片比如“12345.jpg”,以流的方式到了servlet里。我怎么接收它,然后,用system.out打印出来。我要一下代码。

追答 //创建一个磁盘文件的工厂,然后将它 传递到servletFileUplaod的实例中  
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();  
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

参考技术A 不要那么做费时费力啊,图片直接上传到一个目录下,然后只要知道路径就能加载了,数据库保存个路径就好了,其它的都可以得到了

java实现图片上传至服务器并显示,如何做?

目标很简单,通过JSP页面让用户选择本地图片文件,提交就上传到服务器保存。上传成功的话JSP页面上就显示刚上传的图片。

我自己想了一下,觉得有两种办法可以试试:
1、服务器把图片作为blob型数据存进数据库,然后显示的时候就查数据库取出来送到JSP
2、服务器把图片作为文件保存到服务器某个文件夹,例如upload文件夹,然后把图片的路径名作为varchar型保存到数据库中。显示的时候就到数据库中查找路径名,处理后赋值给<img>的src属性

我想知道的是:
1、服务器端怎么从浏览器接收文件,通过流吗?如果是流那么用什么流呢?字节流、字符流或者其它的高级流?服务器接收到的文件是个什么样子?例如上传的是jpg图片,服务器最初接收到的就是.jpg的文件吗?

2、对于第一种实现方法,把blob数据从数据库取出来之后是什么样子?例如当初jpg图片作blob存进去的,取出来之后就是jpg的吗?还是要通过什么方法做成jpg?如果要做,怎么弄呢?常见的网页显示图片代码是<img src='图片URL'>,如果是数据库取出来的图片文件,要怎么在JSP中显示?

3、对于第二种实现方法,如果第一个问题解决的话,我自己琢磨吧。感觉这个方法好理解一些

-----------------------------------------------------------------
最好能有具体代码说明一下怎么做的,谢谢!!!

给你段代码,是用来在ie上显示图片的(servlet):

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
String id = request.getParameter("id");
File file = new File(getServletContext().getRealPath("/")+"out"+"/"+id+".gif");
response.setCharacterEncoding("gb2312");
response.setContentType("doc");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));

System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));

OutputStream output = null;
FileInputStream fis = null;
try

output = response.getOutputStream();
fis = new FileInputStream(file);

byte[] b = new byte[1024];
int i = 0;

while((i = fis.read(b))!=-1)


output.write(b, 0, i);

output.write(b, 0, b.length);

output.flush();
response.flushBuffer();

catch(Exception e)

System.out.println("Error!");
e.printStackTrace();

finally

if(fis != null)

fis.close();
fis = null;

if(output != null)

output.close();
output = null;





这个程序的功能是根据传入的文件名(id),来为浏览器返回图片流,显示在<img>标签里
标签的格式写成如下:
<img src="http://localhost:8080/app/preview?id=111 "/><br/>
显示的是111.gif这个图片

你上面的问题:
1.我觉得你的第二个办法是对的,我们也是这样做的,需要的是把数据库的记录id号传进servlet,然后读取这条记录中的路径信息,生成流以后返回就是了

关于上传文件的问题,我记得java中应该专门有个负责文件上传的类,你调用就行了,上传后存储在指定的目录里,以实体文件的形式存放
你可以参考这个:
http://blog.csdn.net/arielxp/archive/2004/09/28/119592.aspx

回复:
1.是的,在response中写入流就行了
2.是发到servlet中的,我们一般都是写成servlet,短小精悍,使用起来方便,struts应该也可以,只是我没有试过,恩,你理解的很对
参考技术A 网上可以下到上传控件。。都是写好的 我这也有 太长了就不发上来了 你要是要我可以给你 你只要在servlet里调用里面的方法就行了 参考技术B   使用一些已有的组件帮助我们实现这种上传功能。
  常用的上传组件:
    Apache 的 Commons FileUpload
    JavaZoom的UploadBean
    jspSmartUpload
以下,以FileUpload为例讲解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然后只需要放置一个file控件,并执行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext())
FileItem item = (FileItem) itr.next();
if (item.isFormField())
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
else
if (item.getName() != null && !item.getName().equals(""))
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
else
request.setAttribute("upload.message", "没有选择上传文件!");



catch(FileUploadException e)
e.printStackTrace();
catch (Exception e)
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");

request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
参考技术C 用common-fileupload几行代码搞定 参考技术D public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
RecordForm rform=(RecordForm)form;
FormFile formFile=rform.getImage();
String path=request.getSession().getServletContext().getRealPath("/");
RecordService service=(RecordService) BeanFactory.getBean(BeanFactory.RECORDSERVICE);
StudentService stuservice=(StudentService) BeanFactory.getBean(BeanFactory.STUDENTSERVICE);
Student student=(Student) request.getSession().getAttribute("student");
Record record=(Record) request.getSession().getAttribute("record");
student.setName(rform.getName());
student.setGender(rform.getGender());
record.setAddress(rform.getAddress());
record.setAdmitdate(Date.valueOf(rform.getAdmitdate()));
record.setBirthday(Date.valueOf(rform.getBirthday()));
record.setFromaddr(rform.getFromaddr());
record.setRemarks(rform.getRemarks());
record.setFeature(rform.getFeature());
record.setStudent(student);
student.setRecord(record);
if(formFile.getFileSize()!=0)
String image=getPath(formFile,path,student.getId());
record.setImage(image);

try
stuservice.updateStudent(student);
service.updateRecord(record);
request.setAttribute("record", record);
request.setAttribute("student", student);
return mapping.findForward("success");
catch (ServiceException e)
request.setAttribute("error", e.getMessage());
e.printStackTrace();
return mapping.findForward("failure");


private String getPath(FormFile formFile, String path, String studentid)
InputStream is = null;
FileOutputStream fos = null;
File file = new File(path + "/" + studentid + "/");
if (!file.exists())
file.mkdir();
try
is = formFile.getInputStream();
fos = new FileOutputStream(path + "/" + studentid + "/"
+ formFile.getFileName());
byte[] buffer = new byte[8092];
int count = 0;
while ((count = is.read(buffer, 0, buffer.length)) != -1)
fos.write(buffer, 0, count);
catch (FileNotFoundException e)
// TODO Auto-generated catch block
e.printStackTrace();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();
finally
try
if (is != null)
is.close();
if (fos != null)
fos.close();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();



return "/"+ studentid+"/"+formFile.getFileName();



用struts做的,在JSP页面中用fromFile标签

以上是关于java:servlet接收图片,并把它保存到数据库中的主要内容,如果未能解决你的问题,请参考以下文章

resty.upload 处理上传的图片 并把生成的url保存到数据库中

java servlet如何接收其他程序传来的图片和参数!

java api 接收保存图片到本地

java api 接收保存图片到本地

java 后台如何获取前台上传的几张图片

java存储富文本到啥数据库