servlet实现文件的上传和下载

servlet实现文件的上传和下载

jsp表单提交页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
         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>
    <base href="<%=basePath%>">

    <title>上传的页面</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
        <form  action="${pageContext.request.contextPath }/ServletUploadFile.action" method="post" enctype="multipart/form-data" >
                用户名1: <input  type="text"   name="username" value="usernamevalue" ><br>
            用户名2:     <input   type="text"   name="username2"  value="username2value"><br>
          请选择文件:  <input   type="file"   name="fileUpload"  ><br>
            <input  type="submit"   value="上传"><input   type="reset"   value="重置">
        </form>     
  </body>
</html>

上传文件servlet代码块

package cn.kaka.web.content;

import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *   文件的上传
 * 
 * @author myluo
 *
 */
public class ServletUploadFile extends  HttpServlet{

     /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
             doPost(req, resp);
    }


     @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         try {
            //设置request作用域的编码格式
            request.setCharacterEncoding("UTF-8");
            //设置response作用域的值
            response.setContentType("text/html; charset=UTF-8");
            //初始化磁盘工厂
            DiskFileItemFactory dfif = new DiskFileItemFactory();
            //设置临时上传的路径,这里用的是相路径
            String itemPath = "/myluo";
            //根据这个路径创建一个文件
            File f = new File(itemPath);
            //判断此文件的在此路径目录是否存在,如果不存在,创建文件夹
            if (!f.exists()) {
                //创建文件所需的目录
                f.mkdirs();
            }
            //设置上传文件临时目录
            dfif.setRepository(f);
            //设置缓冲区大小
            dfif.setSizeThreshold(4 * 1024 * 1024);//缓存大小为4M
            //初始化上传组件
            ServletFileUpload sfu = new ServletFileUpload(dfif);
            //设置上传文件的大小
            sfu.setFileSizeMax(6 * 1024 * 1024);//最大上传为6M
            //开始解析上传的文件,达到list集合
            List <FileItem> parseRequest = sfu.parseRequest(request);
            //获取表单提交的数量
            System.out.println("jsp页面表单提交input数量:"+parseRequest.size());
            //循环遍历list集合
            for(FileItem  ff:parseRequest){
                //System.out.println("获取的是name"+ff.getFieldName()+":value值"+ff.getString());
                //判断是否是上传文件
                if(ff.getFieldName().equals("fileUpload")){
                    //获取上传文件名字
                    String name = ff.getName();
                    //文件保存的相对路径
                    String  filePath="/myfei/";
                    //根究相对路径构建决对路径
                    String realPath = request.getSession().getServletContext().getRealPath(filePath);
                    System.out.println("写入流的绝对路径:"+realPath);
                    //根究绝对路径创建文件
                    File fe=new  File(realPath);
                     //判断创建文件的目录是否存在
                    if(!fe.exists()){
                        //不存在就构建
                        fe.mkdirs();
                    }
                    //根究文件的名字和路径创建
                    File  obj=new File(realPath,name);
                    //开始把上传的文件写入
                    ff.write(obj);
                    System.out.println("path="+realPath+name);
                    //把文件保存的路径存到request作用域
                    request.setAttribute("path", filePath+name);

                }else{

                    //System.out.println("我不是上传文件的值:"+ff.getString());
                    //获取表单提交的值,中文乱码处理
                    System.out.println(new String(ff.getString().getBytes("ISO-8859-1"),"UTF-8"));

                }


            }



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


         //上传成功以后转发到另一个jsp页面显示
          request.getRequestDispatcher("mini.jsp").forward(request, response);
    }

}

转发显示的jsp页面mini页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"
        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>
    <base href="<%=basePath%>">

    <title>显示上传文件的界面</title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>

  <body>
            <p>显示上传文件</p>
            <p>${path }</p>
            <p>${pageContext.request.contextPath }${path }</p>
            <img height="500px"  whith="500px" src="${pageContext.request.contextPath }${path }"  alt="美丽的苹果"  > 
            <p><a  href="${pageContext.request.contextPath }/ServletFileDownload.action?path=${path}">下载</a></p>
  </body>
</html>

servlet文件下载代码块

package cn.kaka.web.content;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

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

public class ServletFileDownload extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("========================xxxxx");
        //设置编码格式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;chaset=UTF-8");
        //获取从链接地址上传来的相对路径
        String parameter = request.getParameter("path");
        System.out.println("相对路径:"+parameter);

        //根究相对路径构建绝对路径
        String realPath = request.getSession().getServletContext().getRealPath(parameter);
        System.out.println("绝对路径:"+realPath);
        //根究绝对路径获取输入流对象
        FileInputStream  fim=new FileInputStream(realPath);
        //使用输出流往浏览器输出数据
        ServletOutputStream sos = response.getOutputStream();
        //设置要保存的文件
        String filename = parameter.substring(parameter.lastIndexOf("/")+1);
        System.out.println("文件名字:"+filename);
        //设置头文件
        response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));

        int   len=-1;

        byte  []  bt=new  byte[1024];
        while((len=fim.read(bt))!=-1){
            sos.write(bt,0,len);
        }

        fim.close();
        sos.close();
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值