simple file upload

类别:Java 点击:0 评论:0 推荐:


fileup_in.jsp  //单文件上传

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<jsp:useBean id="test" scope="page" class="test.DBconn"/>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>

<body>
<%
   
   try{
        String dir=request.getRealPath(".");
        DiskFileUpload fu = new DiskFileUpload();
  
       
        fu.setSizeMax(4194304);                 //设置文件大小.

        fu.setSizeThreshold(4096);              //设置缓冲大小.

        fu.setRepositoryPath(dir+"/test");      //设置临时目录.
 
        List fileItems = fu.parseRequest(request);  //解析请求,返回一个集合.
       

        Iterator i = fileItems.iterator();
        String fieldvalue="";
        String ff = "";
  Object tt = "";
  Vector v = new Vector();
        while(i.hasNext())
     {
    
         FileItem fi = (FileItem)i.next();
 
    if(fi.isFormField())                        //这是用来确定是否为文件属性,
     {
     
     String fieldName = fi.getFieldName();     //这里取得表单名
     fieldvalue=fi.getString();        //这里取得表单值
     
  v.addElement(fieldvalue);
    
 // out.print("<br>1");
    // out.print("name:"+fieldName);
    // out.print("value:"+fieldvalue);
 
    
    // System.out.println(fieldvalue);
 
     }
 
     else                                           //这里开始外理文件
  {
  
   File fullFile = new File(fi.getName());
      File savedFile = new File(getServletContext().getRealPath("/test/images/"),fullFile.getName());
   ff = fullFile.getName();
 
   fi.write(savedFile);     //上传到服务器
    
       }
      
   }
    //将数据写入到数据库
    tt = v.elementAt(0);
    Object name = v.elementAt(1);
    Object down = v.elementAt(2);
    Object seqno = v.elementAt(3);
   // System.out.println(down);
    java.util.Date date = new java.util.Date();
       String strdate = date.toLocaleString();
    String url = tt + "/";
       //int down = 20;
       try
   {
            String sql = "insert into picture(kid,pic_name,pic_url,pic_downs,pic_date,seqno)values('"+tt+"','"+name+"','"+ff+"','"+down+"','"+strdate+"','"+seqno+"')";
            test.executeUpdate(sql);
   }
   catch(Exception e)
   {
      out.println("insert into db error!");
   }
   }
  catch(Exception e)
   {}

      
 %>
<script language="javascript">
   alert("上传成功了,请返回!");window.location.reload("fileup.jsp");
</script>
</body>
</html>

 

本文地址:http://com.8s8s.com/it/it14109.htm