小女子已用fileupload上传图像到sql server数据库中了,可不知怎么让他显示出来!下面是我上传图片的代码,如果有错,请指出,若无错,能否请教从sql server输出图像的方法?
     in=fileItem.getInputStream();
     size=(int)fileItem.getSize();
     filetype=fileItem.getContentType();
     PreparedStatement pst=null;
     Connection conn=null;
     try{
       conn=image.database.getconnection();
       if(conn!=null)
         System.out.println("connection is ok!!!!");
       String sql="insert into test_img([id],[name],img,filetype) values(?,?,?,?)";
       pst=conn.prepareStatement(sql);
       
       pst.setInt(1,1);
       pst.setString(2,"photoname");
       pst.setBinaryStream(3,in,size);
       pst.setString(4,filetype);
       int nResult=pst.executeUpdate();
      System.out.println("文件上传成功!!!");
或者给我提供正确的源代码也可以,先谢过了!!

解决方案 »

  1.   

    如果上面的代码看不太懂的话,下面是完整的代码:
    public void doPost(HttpServletRequest request, HttpServletResponse response)
       throws ServletException, IOException {
     
      request.setCharacterEncoding("gbk");
      RequestContext requestContext = new ServletRequestContext(request);
      if(FileUpload.isMultipartContent(requestContext)){
       DiskFileItemFactory factory = new DiskFileItemFactory();
       factory.setRepository(new File("c:/tmp/"));
       ServletFileUpload upload = new ServletFileUpload(factory);
       //upload.setHeaderEncoding("gbk");
       upload.setSizeMax(2000000);
       List items = new ArrayList();
        try {
         items = upload.parseRequest(request);
        } catch (FileUploadException e1) {
         System.out.println("文件上传发生错误" + e1.getMessage());
        }   Iterator it = items.iterator();
      InputStream in=null;
      String name=null,filetype=null;
      int size=0;
       while(it.hasNext()){
        FileItem fileItem = (FileItem) it.next();
        if(fileItem.isFormField()){
         System.out.println(fileItem.getFieldName() + "   " + fileItem.getName() + "   " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk"));
        }else{
         System.out.println(fileItem.getFieldName() + "   " +
            fileItem.getName() + "   " +
            fileItem.isInMemory() + "    " +
            fileItem.getContentType() + "   " +
            fileItem.getSize());     if(fileItem.getName()!=null && fileItem.getSize()!=0){
         in=fileItem.getInputStream();
         size=(int)fileItem.getSize();
         filetype=fileItem.getContentType();
         PreparedStatement pst=null;
         Connection conn=null;
         try{
           conn=image.database.getconnection();
           if(conn!=null)
             System.out.println("connection is ok!!!!");
           String sql="insert into test_img([id],[name],img,filetype) values(?,?,?,?)";
           pst=conn.prepareStatement(sql);
           
           pst.setInt(1,3);
           pst.setString(2,"photoname");
           pst.setBinaryStream(3,in,size);
           pst.setString(4,filetype);
           System.out.println("to here----------");
           int nResult=pst.executeUpdate();
          System.out.println("文件上传成功!!!");
          pst.close();
           conn.close();
           
         }catch(Exception e){
           e.printStackTrace(System.err);
         }
     
         }else{
          System.out.println("文件没有选择 或 文件内容为空");
         }
        }
    再次谢过大家
      

  2.   

    javadesigner(以前搞java现在被java搞) 太刻薄了吧,女的怎么了,女的就比你差么...,就算是恐龙,就不能搞IT了?谁说的只有MM才能搞IT的,晕倒。
      

  3.   

    image??就是存图片吧?
    那real呢?是不是电影????
    -_-
      

  4.   

    楼上lovejordan()说的很在理,可以采用。(个人观点)
      

  5.   

    用SmartUpload上传文件到服务器文件系统就ok了。
    上网搜一下,例子很多的
      

  6.   

    此小女子可是心胸宽阔,度量很大。呵呵。不像某些所谓的男人,大有丢我们男人脸的嫌疑。lovejordan(枫剑苍月) 提供的思路已经很明了了,我想你稍加研究应该没问题。作技术的就该自己多动手吧我想。
      

  7.   

    输入是否有误只需打开数据库看看便可,若有数据,大致就是没错的了。
    关于输出的函数,提供一种思路,大致如下:
            protected void get_image()
            {
                string connString = ......; //这里是连接字符串,省略
                int photoId = .......;  //这里是图片在数据库中的id
                SqlConnection connection = new SqlConnection(connString);
                string sqlStr = "SELECT [列名(图片数据流)] from [表名] where photoId = " + @photoId;  //查询字符串
                SqlCommand command = new SqlCommand(sqlStr, connection);
                command.Parameters.AddWithValue(new SqlParameter("@photoId", photoId));  //设定sqlStr中的输入参数
                connection.Open();
                Stream stream = null;
                object result = command.ExecuteScalar();  //查询结果是一个ojbect
                stream = new MemoryStream((byte[]) result); //将result 转换为一个二进制字节数组,并创建stream
                const int buffersize = 1024*16; //设置图片大小
                byte[] buffer = new byte[buffersize];  //创建二进制字节数组buffer
                int count = stream.Read(buffer, 0, buffersize);  //将buffer的长度赋给count
                while(count >0)  //循环语句输出buffer的内容
                {
                    Response.OutputStream.Write(buffer, 0, count);  //做网站用Response,做应用程序就要用标准输入输出console
                    count = stream.Read(buffer, 0, buffersize);
                }
            }//----------------------仅供参考--------------------
      

  8.   

    不会弄。鄙视“小女子”的帖子是 CSDN 的优良传统。
      

  9.   

    用blob来存储,
    显示的时候用流来读取大家是真不懂,
    还是再逗mm玩?随手找了个例子,
    mm好好研究一下http://www.blog.edu.cn/user2/dchcuckoo/archives/2006/1151415.shtml
      

  10.   

    Statement stmt = con.createStatement();String sql = " SELECT * FROM PHOTO WHERE photo_no = "+ photo_no;
    ResultSet rs = stmt.executeQuery(sql);
    if (rs.next()) {
    Blob b = rs.getBlob("photo_image");
    long size = b.length();
    //out.print(size);
    byte[] bs = b.getBytes(1, (int)size);
    response.setContentType("image/jpeg"); 
    OutputStream outs = response.getOutputStream(); 
    outs.write(bs);
    outs.flush();
    rs.close(); 
      

  11.   

    大家好啊,感谢楼上所有同志!
    我根据楼上的指导,写了个输出图像的jsp,不过遇到很奇怪的问题:
    我的机子上配有两个tomcat5,其中一个是自己装的,一个是装jbuilder2006时自带的,该程序在jbuilder2006中不能运行,提示错误为:
    java.io.IOException: [Microsoft][SQLServer 2000 Driver for JDBC]Object has been closed.
    at com.microsoft.jdbc.base.BaseInputStreamWrapper.validateClosedState(Unknown Source)
    at com.microsoft.jdbc.base.BaseInputStreamWrapper.read(Unknown Source)
    at com.microsoft.jdbc.base.BaseInputStreamWrapper.read(Unknown Source)
    而在另一个服务器上可以成功运行,关于数据库连接的我有把握没问题,请问大家一下这是什么问题,以下是我输出图像的代码:<%
    try{
    Connection conn=image.database.getconnection();
    Statement st=conn.createStatement();
    String sql="select * from test_img where [id]=1";
    ResultSet rs=st.executeQuery(sql);
    st=conn.createStatement();
    while(rs.next()){
      InputStream in=rs.getBinaryStream("img");
      String filetype=rs.getString("filetype");
      response.setContentType(filetype);  
      out.clear(); 
      out = pageContext.pushBody();
    ServletOutputStream   sout   =   response.getOutputStream();
      if(in!=null)
      {
        byte[] buf=new byte[0x7a120];
        while(true)
        {
          int nRead=in.read(buf);
          if(-1==nRead)
          break;
          sout.write(buf,0,nRead);
        }
        sout.flush();
        sout.close();
        in.close();
      }
    }rs.close();
    st.close();
    conn.close();
    }catch(Exception e){
    e.printStackTrace();
    }
    %>再次谢过大家了!!!
      

  12.   

    tomcat可能对这个处理有点问题,建议用weblogic来调试这段代码
      

  13.   

    package net.seasky.music; import javax.servlet.*; 
    import javax.servlet.http.*; 
    import java.io.*; 
    import java.util.*; 
    import java.sql.*; 
    import net.seasky.util.*; 
    import net.seasky.database.DbConnectionManager; public class CoverServlet extends HttpServlet { 
    private static final String CONTENT_TYPE = "image/gif"; 
    public void init(ServletConfig config) throws ServletException { 
    super.init(config); 
    } public void doGet(HttpServletRequest request, HttpServletResponse response 
    ) throws ServletException, IOException { 
    response.setContentType(CONTENT_TYPE); 
    int albumID; 
    ServletOutputStream out = response.getOutputStream(); 
    try { 
    albumID = ParamManager.getIntParameter(request,"albumID",0); 

    catch (Exception e) { 
    response.sendRedirect("http://www.kissjava.com/doc/J2EE/jdbc_jdo/images/h00/h39/ErroePage.jsp"); 
    return; 

    try { 
    InputStream in=this.getCover(albumID); 
    int len; 
    byte buf[]=new byte[1024]; 
    while ((len=in.read(buf,0,1024))!=-1) { 
    out.write(buf,0,len); 


    catch (IOException ioe) { 
    ioe.printStackTrace() ; 

    } private InputStream getCover(int albumID) { 
    InputStream in=null; 
    Connection cn = null; 
    PreparedStatement pst = null; 
    try { 
    cn=DbConnectionManager.getConnection(); 
    cn.setCatalog("music"); 
    pst=cn.prepareStatement("SELECT img FROM cover where ID =?"); 
    pst.setInt(1,albumID); 
    ResultSet rs=pst.executeQuery(); 
    rs.next() ; 
    in=rs.getBinaryStream("img"); 

    catch (SQLException sqle) { 
    System.err.println("Error in CoverServlet : getCover()-" + sqle); 
    sqle.printStackTrace() ; 

    finally { 
    try { 
    pst.close() ; 
    cn.close() ; 

    catch (Exception e) { 
    e.printStackTrace(); 


    return in; 
    } public void destroy() { 

    }
      

  14.   

    http://www.blog.edu.cn/user2/dchcuckoo/archives/2006/1151415.shtml
      

  15.   

    String sql="insert into test_img([id],[name],img,filetype) values(?,?,?,?)";
    z这样能把图片存到数据库中,第一次见,强
      

  16.   

    编码存可以,并非象楼上所说,1mb就是db中1mb,小得很,要实践,具体代码我着还没有但直接insert是不行的,upload有漏洞,如果有图片文件重名,就会覆盖,导致文件混乱
      

  17.   

    String sql="insert into test_img([id],[name],img,filetype) values(?,?,?,?)";
    z这样能把图片存到数据库中,第一次见,强可以存啊,我已存到数据库中了
      

  18.   

    支持   lovejordan(枫剑苍月)
      

  19.   

    回复人:lovejordan(枫剑苍月) ( 一级(初级)) 信誉:100  2006-10-9 14:24:14  得分:0
    ?  同学,上传代码比较好的就是在服务器端建立一个专用的图片文件夹,图片上传到些文件夹里面,往数据库里传的是这个文件夹在服务器端的相对路径以及图片名称,这样在前端提取图片的时候只需要调用路径就可以了就是这样的import java.awt.image.BufferedImage;
    import java.io.*;import javax.imageio.ImageIO;
    import javax.servlet.*;
    import javax.servlet.http.*;import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;public class Showpic extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    this.showpic("d:\\tomcat.jpg",response);

    } private void showpic(String picname,
    HttpServletResponse response) throws ServletException, IOException {
    ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
    BufferedImage bufferImg = ImageIO.read(new File(picname));
    ImageIO.write(bufferImg, "jpg", byteArrayOut);
    ServletOutputStream sos = response.getOutputStream();
    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
    encoder.encode(bufferImg); }
    }
    这里建议不用BufferedImage,直接读出来
      

  20.   

    问题已差不多解决了,感谢楼上所有人的帮助,
    特别是qiuqiupeng(老玩童) ;guo__peng(guo__peng) ;bolice() ;lovejordan(枫剑苍月) 
    等几位的帮助
    结帖了!!!