• jsp和servlet实现文件的上传和下载


    一、项目文件夹和所需jar包


     

    二、文件上传:

     index.jsp 文件代码:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
      <title>File upload</title>
    </head>
    <body>
    <form action="${pageContext.request.contextPath}/Upload" enctype="multipart/form-data" method="post">
      上传用户:<input type="text" name="username"><br/><br/>
      上传文件1:<input type="file" name="file1"><br/><br/>
      上传文件2:<input type="file" name="file2"><br/>
      <input type="submit" value="提交">
    </form>
    </body>
    </html>

    Upload.java文件代码:

    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.List;
    
    @WebServlet("/Upload")
    public class Upload extends HttpServlet {
    
        public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //得到上传文件的保存目录,将上传的文件存放在WEB-INF目录下面 不允许外界直接访问,保证上传文件的安全性
            String savePath = this.getServletContext().getRealPath("WEB-INF/file");
            System.out.println(savePath);
            req.setCharacterEncoding("utf-8");
            File file  =new File(savePath);
            if(!file.exists()&&!file.isDirectory()){ //判断路径是否存在,路径不存在则创建路径
                System.out.println(savePath+"目标目录不存在,需要进行创建");
                file.mkdir();
    
            }
            String message = null;
            try {
                //1 创建DiskFileItemFactory工厂
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //2 创建一个文件上传解析器
                ServletFileUpload upload = new ServletFileUpload(factory);
                //判断提交上来的数据是不是表单上的数据
                upload.setHeaderEncoding("UTF-8");
                boolean mt = ServletFileUpload.isMultipartContent(req);
                System.out.println(mt);
                if (!ServletFileUpload.isMultipartContent(req)) {
                    System.out.println("非表单数据!");
                    return;
                }
    
                //4 使用ServletFileUpload解析器来解析上传数据,解析结果返回的是一个List<FileItem>
                //集合,每一个FileItem对应一个Form表单的输入项
                List<FileItem> list = upload.parseRequest(req);
                for(FileItem item:list) {
                    if (item.isFormField()) { //如果表单中有普通类型便签则为true
                        String name = item.getFieldName(); //获取表单中普通标签的name属性
                        String value = item.getString("UTF-8");
                        System.out.println(name + "=" + value);
                    } else {
                        String filename = item.getName();
                        System.out.println(filename);
                        if (filename == null || filename.trim().equals("")) {
                            continue;
                        }
                        //注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如:  c:a1.txt,而有些只是单纯的文件名,如:1.txt
                        //处理获取到的上传文件的文件名的路径部分,只保留文件名部分
                        filename = filename.substring(filename.lastIndexOf("\") + 1);
                        //获取item输入流
                        InputStream inputStream = item.getInputStream();
                        //创建一个文件输出流
                        FileOutputStream fileOutputStream  =new FileOutputStream(savePath+"\"+filename);
                        //创建一个缓冲区
                        byte buffer[] = new byte[1024];
                        //判断输入流是否已经读完的标识
                        int len = 0;
                        while ((len=inputStream.read(buffer))>0)
                        {
                            fileOutputStream.write(buffer,0,len);
                        }
                        inputStream.close();
                        fileOutputStream.close();
                        item.delete();
                        message = "文件上传成功";
    
    
    
                    }
                }
            }catch (Exception e)
            {
                message = "文件上传失败";
                e.printStackTrace();
            }
            req.setAttribute("message",message);
            req.getRequestDispatcher("WEB-INF/message.jsp").forward(req,resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
        }
    }

    页面提交上传文件:

     

    上传成功:


    三、文件下载:

    <%--
      Created by IntelliJ IDEA.
      User: ibear
      Date: 2020/9/9
      Time: 15:25
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>Title</title>
        <script>
            function doDownload()
            {
                var fileName = "C:\Users\ibear\Desktop\Java\upload\web\WEB-INF\lib\";
                var filePath = "commons-fileupload-1.4.jar";
                return window.location.href=encodeURI("./docdownload.jsp?fName="+encodeURIComponent(fileName)+"&fPath="+encodeURIComponent(filePath));
            }
        </script>
    </head>
    <body>
    <a href="javascript:doDownload()" style="color: dodgerblue"><u>下载</u></a>
    </body>
    </html>
    <%--
      Created by IntelliJ IDEA.
      User: ibear
      Date: 2020/9/9
      Time: 15:31
      To change this template use File | Settings | File Templates.
    --%>
    
    <%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*,java.util.Locale" pageEncoding="UTF-8"%>
    <%
        //关于文件下载时采用文件流输出的方式处理:
        //加上response.reset(),并且所有的%>后面不要换行,包括最后一个;
        //因为Application Server在处理编译jsp时对于%>和<%之间的内容一般是原样输出,而且默认是PrintWriter,
        //而你却要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制,
        //就会发生:getOutputStream() has already been called for this response的错误
        //详细请见《More Java Pitfill》一书的第二部分 Web层Item 33:试图在Servlet中使用两种输出机制 270
        //而且如果有换行,对于文本文件没有什么问题,但是对于其它格式,比如AutoCAD、Word、Excel等文件
        //下载下来的文件中就会多出一些换行符0x0d和0x0a,这样可能导致某些格式的文件无法打开,有些也可以正常打开。
        response.reset();//可以加也可以不加
        response.setContentType("application/x-download");//设置为下载application/x-download
        // /../../退WEB-INF/classes两级到应用的根目录下去,注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/
        String fName = request.getParameter("fName");
        String fPath = request.getParameter("fPath");
        String filenamedownload = fPath;//需要下载的文件
        String filenamedisplay = fName;//默认保存文件名
        filenamedownload = URLDecoder.decode(fName,"utf-8");
        filenamedisplay = URLDecoder.decode(fPath,"utf-8");
        //处理由于AIX上中文变乱码,导致判断文件是否存在不准确
        String osName = System.getProperty("os.name");
        if("AIX".equals(osName.toUpperCase(Locale.ENGLISH))){
            try {
                filenamedownload = new String(filenamedownload.getBytes("GBK"),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
            }
        }
        response.addHeader("Content-Disposition", "attachment;filename=" + new String((filenamedisplay).getBytes("GBK"), "ISO8859-1"));
        OutputStream output = null;
        FileInputStream fis = null;
        try {
            output = response.getOutputStream();
            fis = new FileInputStream(filenamedownload);
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = fis.read(b)) > 0) {
                output.write(b, 0, i);
            }
            output.flush();
            if (output != null) {
                output.close();
                output = null;
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
            if (output != null) {
                output.close();
                output = null;
            }
        }
    %>
    
    

    下载成功:

     


  • 相关阅读:
    C#操作Word打印
    判断文件名是否有效
    Windows系统下的程序开机自启
    Winform应用程序使用自定义的鼠标图片
    C# 操作网络适配器
    Runtime Error! R6025-pure virtual function call
    Winform中跨线程访问UI元素的方法
    C#自定义属性转换类---类型转换器
    获取计算机硬件信息
    获取程序集信息
  • 原文地址:https://www.cnblogs.com/ibear/p/13640189.html
Copyright © 2020-2023  润新知