文件上传,下载

10 篇文章 0 订阅
7 篇文章 0 订阅

1.文件上传
   步骤:
   (1)在web页面中添加上传输入项
   (2)在servlet中读取上传文件的数据,并保存到服务器中。
   
  ---jsp 页面 

  <form action="FileUpServlet" enctype="multipart/form-data" method="post">
          上传文件<input type="file" name="f1">
     <input type="submit" value="上传">     
  </form>


  ---servlet
    

@WebServlet("/FileUpServlet")
    @MultipartConfig(location="/file") //  location在服务器的work下的路径,如果该文件不存在则报错
    public class FileUpServlet extends HttpServlet
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf8");
            response.setCharacterEncoding("utf8");
            response.setContentType("text/html;charset=utf-8");
            //接收上传的文件数据
            Part file=request.getPart("f1");
            String ftype=file.getContentType();
            String fname=file.getSubmittedFileName();
            long fsize=file.getSize();
            System.out.println("文件名"+fname);
            System.out.println("文件类型"+ftype);
            System.out.println("文件大小"+fsize);
            //保存到服务器
            String path=request.getServletContext().getRealPath("file");
            System.out.println(path);
            file.write(path+"/"+fname);//保存
            
            request.setAttribute("logo", fname);
            request.getRequestDispatcher("showfile.jsp").forward(request, response);;
            
        }


    
//练习:完成上传单个文件功能代码,要求上传文件类型只能为PNG、JPG类型,单个单位大小不能超过2MB,
       //文件上传到WEB-INF\images目录下,文件名需要重新命名,同时在页面提示上传结果。
      

  <form action="NewfileServlet" enctype="multipart/form-data" method="post">
            name:<input type="text" name="name"><br>
            email:<input type="text" name="email"><br>
            上传文件<input type="file" name="f1"><br>
            <input type="submit" value="上传">
        </form>
        ${msg }

        

@WebServlet("/NewfileServlet")
        @MultipartConfig
        public class NewfileServlet extends HttpServlet {
            protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                request.setCharacterEncoding("utf8");
                response.setContentType("text/html;charset=utf-8");
                PrintWriter out=response.getWriter();
                String name=request.getParameter("name");
                String email=request.getParameter("email");
                Part file=request.getPart("f1");
                //要求上传文件类型只能为PNG、JPG类型,单个单位大小不能超过2MB,
                String fname=file.getSubmittedFileName().toLowerCase();
                long fsize=file.getSize()/1024/1024; //1024*1024B =1024KB=1MB
                
                if(!fname.endsWith("png")&&!fname.endsWith("jpg")){
                    request.setAttribute("msg", "上传文件类型只能为PNG、JPG类型");
                }else if(fsize>2){
                    request.setAttribute("msg", "单位大小不能超过2MB");
                }else{
                    //ok
                    String path=request.getServletContext().getRealPath("WEB-INF/images");
                    //logo1.png
                    System.out.println(fname);
                    String arr[]=fname.split("\\.");  //  实现点用 \. \是转义字符 
                    String newfilename=arr[0]+name+email+"."+arr[1];
                    file.write(path+"/"+newfilename);
                    request.setAttribute("msg", "上传成功!");
                }
                request.getRequestDispatcher("prac1.jsp").forward(request, response);
            }


2.文件下载
   将服务器上某目录下的文件封装到列表中,并显示的过程
   (1)找到文件目录
    (2) 获取文件 File类
   (3)遍历列表并显示
    (4) 选定要下载的文件,根据该文件名,查找对应的文件
    (5) 读文件流,设置响应,获取响应流输出
    (6) 关闭输入流和输出流
    
     //1,2,3
 

   @WebServlet("/DownFileServlet")
    public class DownFileServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //1.获取文件资源
              //目录的路径
            String path=request.getServletContext().getRealPath("file");
            //根据目录,创建文件对象
            File file=new File(path);
            //获取该对象下的所有文件
            File allfiles[]=file.listFiles();
            //2.遍历文件获取所有文件的文件名,封装在list列表中
            List<String> list=new ArrayList();
            for(File f:allfiles){
                list.add(f.getName());
            }
            //3.存放list列表到request中
            request.setAttribute("flist", list);
            request.getRequestDispatcher("showallfiles.jsp").forward(request, response);
        }
    }


    ===showallfiles.jsp  //3.4
   

  <ul>
      <c:forEach items="${flist }" var="ff">
         <li>${ff }<a href="getDownFileServlet?fname=${ff }">下载</a></li>
      </c:forEach>
   </ul>


   //根据文件名 查找文件,封装成输入流,边读边响应输出
   

@WebServlet("/getDownFileServlet")
   public class getDownFileServlet extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //获取要下载的文件名 --url请求参数
        String fname=request.getParameter("fname");
        //响应头设置,创建输出流
            response.setHeader("content-disposition", "attachment;filename="+fname);
            ServletOutputStream output= response.getOutputStream();
        //根据文件名查找文件对象
        String path=request.getServletContext().getRealPath("file/"+fname);
        System.out.println("下载的文件的绝对路径"+path);
        FileInputStream in=new FileInputStream(path);
        //读取流中的信息
        byte[] arr=new byte[1024];
        int len=0;
        while((len=in.read(arr))!=-1){
            //响应输出
            output.write(arr,0,len);
        }
        in.close();
        output.close();
        
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值