这样为什么不行啊,我也是看csdn上别人这样写的,我试了一下不可以的,是哪里错了啊,本人虚心请教,谢谢,在线等!!

解决方案 »

  1.   

    这个是我用过的,你可以参考参考package uploadfile;import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    import java.text.*;/**
     * <p>Title: </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2003</p>
     * <p>Company: </p>
     * @author not attributable
     * @version 1.0
     */public class SaveFile extends HttpServlet
    {
      private static final String CONTENT_TYPE = "text/html; charset=GBK";
      private static final String INSERT = "insert into oka (实验名称,别名,文件名,说明,image) values (?,?,?,?,?)";
      private static final String SELECT_INSERT_ID = "select @@identity as id";
      private static final String SELECT = "select * from oka where id = ?";  boolean hasError = false;
      String fileName = "";                 //文件名
      String fileExt = "";                  //由页面传过来的文件路径和文件名
      byte[] fileData;                      //文件数据
      String nam="";
      String ind="";
      String xuhao="";  //Initialize global variables
      public void init() throws ServletException
      {
      }
      //Process the HTTP Get request
      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
        
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        this.save(request,response);
      }
      //Process the HTTP Post request
      public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {    response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        this.save(request,response);
      }  public void save(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException
      {    response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();    ParsePutFileHttpStream hStream = new ParsePutFileHttpStream(request, response);
        this.nam=(String)hStream.getParams("nam");
        this.ind=(String)hStream.getParams("ind");
        if(hStream.getParams("fileName")!=null) { this.fileName = (String) hStream.getParams("fileName"); }
        //得到文件数据
        this.fileData = hStream.getFileByte();
        //得到物理文件名
        if(hStream.getParams("filename")!=null) { this.fileExt = (String) hStream.getParams("filename"); }
        java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(fileExt, "\\");
        while (tokenizer.hasMoreTokens())
        {
          if (tokenizer.countTokens() == 1)
          {
            this.fileExt = tokenizer.nextToken();
          }
          else
          {
            tokenizer.nextToken();
          }
        }
    ///////////以下判断各数据合法性////////////////////////    //文件物理名或扩展名
        if ("".equals(this.fileExt) || this.fileExt == null)
        {
          this.hasError = true;
          out.println("<script language='javascript'>");
          out.println("alert('文件名不能为空')");
          out.println("window.history.back()");
          out.println("</script>");
        }
        //判断文件数据
        if (this.fileData == null)
        {
          this.hasError = true;
          out.println("<script language='javascript'>");
          out.println("alert('文件不能为空')");
          out.println("window.history.back()");
          out.println("</script>");
        }
        if (this.fileData.length == 0)
        {
          this.hasError = true;
          out.println("<script language='javascript'>");
          out.println("alert('文件长度不能为空')");
          out.println("window.history.back()");
          out.println("</script>");
        }    //文件名称
        if((this.fileName == null)||(this.fileName.equals("")))
        {
          this.hasError = true;
          out.println("<script language='javascript'>");
          out.println("alert('文件别名不能为空')");
          out.println("window.history.back()");
          out.println("</script>");
        }    //保存数据
        try
        {
          this.insertData();
          out.println("</body></html>");
          out.println("<script language='javascript'>");
          out.println("alert('文件上传成功')");
          out.println("window.history.back()");
          out.println("</script>");
        }
        catch (SQLException e)
        {
          out.println("<script language='javascript'>");
          out.println("alert('SQLException:"+e.getMessage()+"')");
          out.println("window.history.back()");
          out.println("</script>");
        }
        catch(Exception e1)
        {
          out.println("<script language='javascript'>");
          out.println("alert('Exception:"+e1.getMessage()+"')");
          out.println("alert('Exception:"+e1.toString()+"')");
          out.println("window.history.back()");
          out.println("</script>");
        }  }  private void insertData() throws SQLException,Exception
       {
         if(!this.hasError)
         {
           Connection con = DatabaseConnection.getConnection();
           byte[] tmp = new byte[4096];
           tmp[0] = this.fileData[0];
           //com.sybase.jdbcx.TextPointer tp = null;
           PreparedStatement pst = null;
           con.setAutoCommit(false);
           try
           {
             pst = con.prepareStatement(this.INSERT);
            // pst.setInteger(1, this.doPost.xuhao);
             pst.setString(1, this.nam);
             pst.setString(2, this.fileName);
             pst.setString(3, this.fileExt);
             pst.setString(4, this.ind);
             pst.setBytes(5,this.fileData);
      
             pst.execute();
             con.commit();
           }
           catch (SQLException e1)
           {
             con.rollback();
             throw new SQLException(e1.toString());
           }
           catch(Exception e)
           {
             con.rollback();
             throw new Exception(e.toString());
           }
           finally
           {
             try
             {
               if (pst != null)
               {
                 pst.close();
                 pst = null;
               }
             }
             catch (SQLException e)
             {}
           }
         }
       }  //Clean up resources
      public void destroy()
      {
      }
    }
      

  2.   

    package uploadfile;import javax.servlet.http.*;
    import javax.servlet.*;
    import javax.naming.*;
    import java.util.*;
    import java.io.*;
    /**
     * <p>Title: </p>
     * <p>Description: </p>
     * <p>Copyright: Copyright (c) 2002</p>
     * <p>Company: </p>
     * @author not attributable
     * @version 1.0
     */public class ParsePutFileHttpStream
    {  private static final char CR = 13;
      private static final char LF = 10;  protected String boundary = null;
      protected Hashtable params = new Hashtable();
      private byte[] fileByte;  public ParsePutFileHttpStream(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
      {
        ServletInputStream in = request.getInputStream();
        BufferedInputStream bin = new BufferedInputStream(in);
        boundary = getBoundary(request.getHeader("content-type"));    PrintWriter out = response.getWriter();
        //out.println("<html><body><pre>");
        //out.println("boundary=\n" + boundary);
        //out.println();    byte[] bytes = new byte[4096];
        in.readLine(bytes, 0, bytes.length);
        String line = new String(bytes);
        Hashtable header = null;
        while (in.readLine(bytes, 0, bytes.length) >= 0)
        {
          line = new String(bytes);
          if (line.startsWith("Content-Disposition:"))
          {
            //out.println(line);
            System.out.println(line);
            header = parseHeader(line);
            updateParams(header);
          }
          else if (line.startsWith("Content-Type:"))
          {
            params.put("Content-Type", line.substring("Content-Type:".length()).trim());
          }
          else
          {
            if (header != null && bytes[0] == 13)
            {
              if (header.containsKey("filename"))
              {
                displayParams(out);
                //out.println("  ...saving payload");
                System.out.println("  ...saving payload");
                paserFileStream(bin);
                header = null;
              }
              else
              {
                String name = (String) header.get("name");
                String value = getParameter(in).trim();
                params.put(name, value);
              }
            }
            if (line.indexOf(boundary) >= 0)
            {
              //out.println(line);
            }
            if (line.indexOf(boundary) >= 0)
            {
              System.out.println(line);
            }
          }
          bytes = new byte[4096];
        }
        //out.println(this.fileByte.length);
      }  private void paserFileStream(BufferedInputStream is) throws IOException
      {
        int c;
        PushbackInputStream input = new PushbackInputStream(is, 4096);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ( (c = read(input, boundary)) >= 0)
        {
          out.write(c);
        }
        fileByte = out.toByteArray();
        out.close();
        input.close();
      }  private String getParameter(ServletInputStream in) throws java.io.IOException
      {
        byte[] bytes = new byte[4096];
        in.readLine(bytes, 0, bytes.length);
        return new String(bytes);
      }  private String getBoundary(String contentType)
      {
        int bStart = contentType.indexOf("boundary=") + "boundary=".length();
        return "" + CR + LF + "--" + contentType.substring(bStart);
      }  private int read(PushbackInputStream input, String boundary) throws IOException
      {
        StringBuffer buffer = new StringBuffer();
        int index = -1;
        int c;    do
        {
          c = input.read();
          buffer.append( (char) c);
          index++;
        }
        while ( (buffer.length() < boundary.length()) && (c == boundary.charAt(index))); if (c == boundary.charAt(index))
        {
          int type = -1;
          if (input.read() == '-')
          {
            type = -2;
          }
          while (input.read() != LF)
          {
            ;
          }
          return type;
        }
        while (index >= 0)
        {
          input.unread(buffer.charAt(index));
          index--;
        }
        return input.read();
      }  private Hashtable parseHeader(String line)
      {
        Hashtable header = new Hashtable();
        String token = null;
        StringTokenizer st = new StringTokenizer(line, ";");
        while (st.hasMoreTokens())
        {
          token = st.nextToken().trim();
          String key = "";
          String val = "";
          int eq = token.indexOf("=");
          if (eq < 0)
          {
            eq = token.indexOf(":");
          }
          if (eq > 0)
          {
            key = token.substring(0, eq).trim();
            val = token.substring(eq + 1);
            val = val.replace('"', ' ');
            val = val.trim();
            header.put(key, val);
          }
        }
        return header;
      }  private void updateParams(Hashtable header)
      {
        for (Enumeration e = header.keys(); e.hasMoreElements(); )
        {
          String key = (String) e.nextElement();
          params.put(key, header.get(key));
        }
      }  private void displayParams(PrintWriter out)
      {
        for (Enumeration e = params.keys(); e.hasMoreElements(); )
        {
          String key = (String) e.nextElement();
          System.out.println("  " + key + " = " + params.get(key));
        }
      }  public byte[] getFileByte()
      {
        return this.fileByte;
      }  public Object getParams(String param)
      {
        return params.get(param);
      }  protected void finalize()
      {
        params.clear();
        params = null;
      }}
      

  3.   

    上面的代码好象错的,而且不是我要的,我要的是向sqlserver放入图片,和读取图片的列子。急急急