Java文件上传与下载2

先是两个主要的servlet//
UploadServlet///

package citiz.net.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;

import citiz.net.bean.LoadBean;

public class UploadServlet extends HttpServlet
{

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
 {
  this.doPost(request, response);
 }


 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException
 {
  String name = null;  //最终用于存放上传文件的文件名
  String descr = null; //用于存放上传文件的描述信息
  String path = "e:\\fileupload";  //上传的目标文件夹
  
  DiskFileUpload disk = new DiskFileUpload(); 
  disk.setSizeMax(1024*1024*5);   //设置上传文件最大size
  disk.setSizeThreshold(1024*512);  //设置cache
  disk.setRepositoryPath("e:\\loadTemp"); //设置临时文件夹
  
  try
  {
   List items = disk.parseRequest(request);
   Iterator it = items.iterator();
   while(it.hasNext())
   {
    FileItem item = (FileItem)it.next();
    if(!item.isFormField())
    {
     //这里的name是客户端上传文件件的全路径(绝对路径)
     name = item.getName();
     int index = name.lastIndexOf("\\");  //用斜杠分割出文件名
     if(index > 0)
     {
      name = name.substring(index+1);  //到这里name才是真正的文件名
     }
     
     File file = new File(path,name);
     item.write(file);  //将文件数据项的内容写到硬盘上
//     path = path + "\\" + name;  //得到上传文件 在服务器 的全路径(准备放入数据库)同下面一句
     path = file.getAbsolutePath();
    }
    else
    {
     descr = item.getString();
     //网络传输用的是iso-8859-1,这里要进行编码转换
     descr = new String(descr.getBytes("ISO-8859-1"),"GBK");
           
   }
//   循环结束后插入数据库
   new LoadBean(path,descr).insertBean();
  }
  catch (FileUploadException e)
  {
   e.printStackTrace();
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
  response.sendRedirect("index.jsp");  
 }

}

 

DownloadServlet///

package citiz.net.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.TreeSet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import citiz.net.bean.LoadBean;

public class DownloadServlet extends HttpServlet
{
 
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
 {
   this.doPost(request, response);
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
 {
  String id = request.getParameter("id");
  TreeSet ts = LoadBean.getAll();   //得到所有记录
//  如果不带id,是要求显示下载页面
  if(id == null)
  {
   response.setContentType("text/html");
   
   request.setAttribute("all", ts.iterator());
   request.getRequestDispatcher("/download.jsp").forward(request, response);
  }
//  其他情况为具体下载一个文件
  else
  {
   LoadBean bean = LoadBean.getBean(Integer.parseInt(id)); //得到id对应的LoadBean对象
   
   File file = new File(bean.getPath()); //封装成File对象
   String fileName = file.getName();  //得到文件名
   int fileLen = (int)file.length();
   //设置响应头信息
   response.setContentType("application/x-msdownload");   
   String str = "attachment;filename=" + fileName;
   response.setHeader("Content-Disposition", str);
   
   response.setContentLength(fileLen);
   
   //分别得到输入输出流
   FileInputStream input = new FileInputStream(file);
   ServletOutputStream out = response.getOutputStream();
   
   byte[] cache = new byte[1024*512];  //设置读写缓存512K
   int len = 0;
   while((len = input.read(cache)) > 0)
   {
    out.write(cache,0,len);
   }
   //关闭流
   input.close();
   out.close();
  }
 }
}

 

以下是其他文件(jsp/bean)

index.jsp/

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>index</title>
</head>
<body>
 <h2 align="center">
  <a href="upload.jsp">upload</a>
  <a href="download">download</a>  
 </h2>
</body>
</html>

 

upload.jsp/

<%@ page language="java" contentType="text/html; charset=GB2312"%>
<html>
<head>
<title>upload</title>
</head>
<body>
        <form action="upload" method="post" enctype="Multipart/form-data">
            <table>
                <tr>
                    <td>upload file's path:</td>
                    <td><input type="file" name="file1" size="40"/></td>
                </tr>
                <tr>
                    <td>file's description:</td>
                    <td><input type="text" name="desc1" size="40"/></td>
                </tr>
               
                <tr>
                    <td><input type="reset" value="reset"/></td>
                    <td><input type="submit" value="upload"/></td>
                </tr>
            </table>
        </form>

</body>
</html>

 

download.jsp/

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<%@ page import="java.util.*,citiz.net.bean.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>download</title>
</head>
<body>
 <%
  Iterator it = (Iterator)request.getAttribute("all");
  while(it.hasNext())
  {
   LoadBean bean = (LoadBean)it.next();
 %>
   <a href="download?id=<%=bean.getId() %>"><%=bean.getDescr() %></a><br />
 <%
  }
  %>
</body>
</html>

 

LoadBean///

package citiz.net.bean;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.TreeSet;

public class LoadBean implements Comparable
{
 private int id;
 private String path;
 private String descr;
 
 public LoadBean(int id, String path, String descr)
 {
  this.id = id;
  this.path = path;
  this.descr = descr;
 }

 public LoadBean(String path, String descr)
 {
  this.path = path;
  this.descr = descr;
 }
 
 //插入数据库
 public boolean insertBean()
 {
  boolean isInsert = false;
  Connection conn = new DataBean().getConn();
  try
  {
   String sql = "insert into uploadInfo values(seq_uploadInfo.nextval,?,?)";
   PreparedStatement pst = conn.prepareStatement(sql);
   pst.setString(1, this.path);
   pst.setString(2, this.descr);
   int flag = pst.executeUpdate();
   if(flag > 0 )
   {
    isInsert = true;
   }
   conn.close();
  }
  catch (SQLException e)
  {
   e.printStackTrace();
  }
  return isInsert;
 }
 //返回所有表记录的集合
 public static TreeSet getAll()
 {
  TreeSet<LoadBean> set = new TreeSet<LoadBean>();
  Connection conn  = new DataBean().getConn();
  try
  {
   Statement st = conn.createStatement();
   ResultSet rs = st.executeQuery("select * from uploadInfo");
   while(rs.next())
   {
    LoadBean bean = new LoadBean( rs.getInt(1),
            rs.getString(2),
            rs.getString(3)
           );
    set.add(bean);
   }
   conn.close();
  }
  catch (SQLException e)
  {
   e.printStackTrace();
  }
  
  return set;
 }
 //通过id得到一个该类对象
 public static LoadBean getBean(int id)
 {
  LoadBean bean = null;
  Connection conn = new DataBean().getConn();
  try
  {
   PreparedStatement pst = conn.prepareStatement("select * from uploadInfo where id=?");
   pst.setInt(1, id);
   ResultSet rs = pst.executeQuery();
   if(rs.next())
   {
    bean = new LoadBean(
         rs.getInt(1),
         rs.getString(2),
         rs.getString(3)
         );
   }
   conn.close();
  }
  catch (SQLException e)
  {
   e.printStackTrace();
  }
  return bean;
 }
 
 public String getDescr()
 {
  return descr;
 }

 public void setDescr(String descr)
 {
  this.descr = descr;
 }

 public int getId()
 {
  return id;
 }

 public void setId(int id)
 {
  this.id = id;
 }

 public String getPath()
 {
  return path;
 }

 public void setPath(String path)
 {
  this.path = path;
 }

 public int compareTo(Object o)
 {
  LoadBean bean = (LoadBean)o;
  if(bean.getId() < this.id)
  {
   return -1;
  }
  else if(bean.getId() > this.id)
  {
   return 1;
  }
  else
  {
   return 0;
  }
 
}


///DataBean//

package citiz.net.bean;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class DataBean
{
 private Connection conn;

 public DataBean()
 {
  try
  {
   InitialContext init = new InitialContext();
   DataSource source = (DataSource)init.lookup("java:comp/env/jdbc/DataSourceOracle");
   conn = source.getConnection();
  }
  catch (NamingException e)
  {
   e.printStackTrace();
  }
  catch (SQLException e)
  {
   e.printStackTrace();
  }
  
 }

 public Connection getConn()
 {
  return conn;
 }

 public void setConn(Connection conn)
 {
  this.conn = conn;
 }
}

 

///oracle.sql/

create table uploadInfo
(
 id int primary key,
 path varchar2(100), --上传文件在服务器的保存路径
 descr varchar2(30)  --上传文件的描述信息
);

create sequence seq_uploadInfo increment by 1 start with 1;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值