jsp+servlet上传和下载

上传:jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page contentType="text/html;charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>文件上传</title>
    <script type="text/javascript">
     function doUplod(){
   var local=document.getElementById("filelocal").value;
   if(local!=null || local!=""){
    document.getElementById("uploadForm").action="UpLoadFileServlet?fileLocal="+local;
   }else{
    document.getElementById("uploadForm").action="UpLoadFileServlet";
   }
   document.getElementById("uploadForm").submit();
     }
    </script>
</head>
<body>
    <br><br>
    <center>
    <font size="5" color="#ff0000"><b>文件上传</b></font><br>
    <form name="uploadForm" id="uploadForm" enctype="multipart/form-data" method="post" action="UpLoadFileServlet">
       <table border="0" align="center" cellpadding="2" cellspacing="2" bgcolor="snow">
          <tr>
             <td>
             <div align="center">上传文件:</div>
             </td>
             <td><div align="center">
                <input type="file" name="uploadfile" id="uploadfile" size="25" maxlength="80">
             </div></td>
          </tr>
          <tr>
             <td>
             <div align="center">存储位置:</div>
             </td>
             <td><div align="center">
                <input type="text" name="filelocal" id="filelocal" size="24" maxlength="80"><font color="red">如:C:\\</font>
             </div></td>
          </tr>
          <tr align="center" width="100%">
             <td align="center" colspan="2">
             <div align="center">
             <input type="button" value="确定">
             <input type="reset" value="清除"></div>
             </td>
          </tr>
          <br/>
          <tr align="center" width="100%">
             <td align="center" colspan="2">
             <div align="center">
    <font style="font-size: 12px"><a href="load.jsp">转入下载</a></font>
             </div>
             </td>
          </tr>
         
       </table>
    </form>
   </center>  
</body>
</html>
 
java code:
package com.qingyun.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UpLoadFileServlet 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 {
  //字符编码级设置
  request.setCharacterEncoding("gbk");
  String fileLocal=request.getParameter("fileLocal");
  if (fileLocal.lastIndexOf(" \\")==-1) {
   fileLocal=null;
  }
  try {
   DiskFileItemFactory factory = new DiskFileItemFactory();
   //设置上传的位置
   ServletFileUpload upload = new ServletFileUpload(factory);
   boolean rest=upload.isMultipartContent(request);
   upload.setHeaderEncoding("UTF-8");
   //设置上传的监听器
   upload.setProgressListener(new ProgressListener() {
          long num = 0;
          public void update(long bytesRead, long contentLength, int items) {
                long progress = bytesRead*100/contentLength;
                if(progress==num){ return;}
                num = progress;
                System.out.println("上传进度:" + progress + "%");
           }
         });
   if(!rest) {
       // 不是文件上传
    request.setAttribute("message", "对不起,不是文件上传表单!");
    request.getRequestDispatcher("/index.jsp").forward(request, response);
       return;
   }
   List<FileItem> fileItems = upload.parseRequest(request);
   File file =null;
   for (FileItem item : fileItems) {
    if(item.isFormField()) {
        String name = item.getFieldName();
        String value = item.getString();
        // 手工的转换了
        value = new String(value.getBytes("iso-8859-1"),"utf-8");
        System.out.println(name + "=" + value);
    } else {
        // 文件上传字段
        // 获得文件名
        String filename = item.getName();
        // 创建文件
        if (fileLocal=="" || fileLocal==null) {
         //默认路径
         file = new File("E:\\"+filename);
     }else{
      //用户填写的路径
      file=new File(fileLocal+filename);      
     }
        file.createNewFile();
        // 获得流,读取数据写入文件
        InputStream in = item.getInputStream();
        FileOutputStream fos = new FileOutputStream(file);
        int len;
        byte[] buffer = new byte[1024];
        while((len=in.read(buffer))>0)
           fos.write(buffer,0,len);
        fos.close();
        in.close();
        item.delete();    // 删除临时文件
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
   request.setAttribute("result", "上传失败,请查找原因,重新再试!");
  }
  request.getRequestDispatcher("/index.jsp").forward(request, response);
 }
}
 
下载:jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page contentType="text/html;charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>下载文件</title>
    <script type="text/javascript">
       function downLoad(){
        var isIE = (document.all) ? true : false;
      var isIE7 = isIE && (navigator.userAgent.indexOf('MSIE 7.0') != -1);
      var isIE8 = isIE && (navigator.userAgent.indexOf('MSIE 8.0') != -1);
      var file=document.getElementById("uploadfile");
      if(isIE7 || isIE8)
      {
          file.select();
          var path=document.selection.createRange().text;
          document.selection.empty();
      }
        document.getElementById("download").href="DownLoadServlet?fileName="+path;
       }
    </script>
</head>
<body>
    <br><br><center>
    <font size="5" color="#ff0000"><b>下载文件</b></font><br>
       <table border="0" align="center" cellpadding="2" cellspacing="2" bgcolor="snow">
          <tr>
             <td>
             <div align="center">
               <input type="file" name="uploadfile" id="uploadfile" size="25" maxlength="80">
             </div>
             </td>
          </tr>
          <tr align="center" width="100%">
             <td align="center" colspan="2">
             <div align="center">
             <a href="" id="download" onclick="downLoad()">下载</a>
             </td>
          </tr>
          <br/>
           <tr align="center" width="100%">
             <td align="center" colspan="2">
             <div align="center">
    <font style="font-size: 12px"><a href="index.jsp">转入上传</a></font>
             </div>
             </td>
          </tr>
       </table>
    </center>  
</body>
</html>
 
java code:
package com.qingyun.test;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownLoadServlet extends HttpServlet {
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
 }
 /*
  * 处理请求 (non-Javadoc)
  * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest ,
  *      javax.servlet.http.HttpServletResponse)
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // 接收中文参数乱码处理
  response.setCharacterEncoding("utf-8");
  String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"), "utf-8");
  System.out.println("文件的路径是:"+fileName);
  // 得到文件名
  // 设置为下载application/x-download
  response.setContentType("application/x-download");
  // 下载文件时显示的文件保存名称
  String filenamedisplay = fileName;
  // 中文编码转换
  filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
  response.addHeader("Content-Disposition", "attachment;filename="+ filenamedisplay);
  try {
   OutputStream os = response.getOutputStream();
   FileInputStream fis = new FileInputStream(
     fileName);
   byte[] b = new byte[1024];
   int i = 0;
   while ((i = fis.read(b)) > 0) {
    os.write(b, 0, i);
   }
   fis.close();
   os.flush();
   os.close();
  } catch (Exception e) {
  }
 }
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns=" http://java.sun.com/xml/ns/javaee"
 xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee
  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>UpLoadFileServlet</servlet-name>
    <servlet-class>com.qingyun.test.UpLoadFileServlet</servlet-class>
  </servlet>
    <servlet-mapping>
    <servlet-name>UpLoadFileServlet</servlet-name>
    <url-pattern>/UpLoadFileServlet</url-pattern>
  </servlet-mapping>
 
 
  <servlet>
    <servlet-name>DownLoadServlet</servlet-name>
    <servlet-class>com.qingyun.test.DownLoadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DownLoadServlet</servlet-name>
    <url-pattern>/DownLoadServlet</url-pattern>
  </servlet-mapping>
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
 
注意:是在j2se5 上 .  有包:commons-fileupload-1.2.1.jar ;commons-io-1.3.2.jar
 

你可能感兴趣的:(职场,上传下载,休闲,jsp+servlet)