展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

javaweb开发(十):文件上传、下载

  • 构建1个web项目,配置tomcat,导入依赖

  • 编写上传页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>

<form action="<%=request.getContextPath()%>/fileUpload" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"/>
    头像:<input type="file" name="img">
    <input type="submit" value="提交">
</form>

</body>
</html>
  • 编写上传的servlet
@WebServlet("/fileUpload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取文件名称
        String username = request.getParameter("username");
        // 获取文件
        Part part = request.getPart("img");
        //获取真实文件名称
        String header = part.getHeader("content-disposition");
        String realFileName = header.substring(header.indexOf("filename=")+10,header.length()-1);
        //获取真实的文件内容
        InputStream is =  part.getInputStream();
        //web-inf目录外界不能直接访问,如果文件机密性强则放这里
        //String dir = this.getServletContext().getRealPath("/WEB-INF/file");
        // 应用上下文路径
        String dir = this.getServletContext().getRealPath("/file");
        File dirFile = new File(dir);
        //如果目录不存在,则创建
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        // 创建名称
        String uniqueName = UUID.randomUUID()+realFileName;
        //文件流拷贝
        File file = new File(dir,uniqueName);
        FileOutputStream out = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf))!=-1 ){
            out.write(buf,0,len);
        }
        // 关闭流
        out.close();
        is.close();
        // 图片访问,转发到图片
        request.getRequestDispatcher("/file/"+uniqueName).forward(request,response);
    }

}
  • 测试


  • 编写下载servlet

@WebServlet("/download")
public class FileDownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //客户端传递需要下载的文件名
        String file = request.getParameter("file");
        //获取文件在我们项目中的路径,发布到tomcat的实际路径
        String path = request.getServletContext().getRealPath("/file/");
        String filePath = path+file;
        FileInputStream fis = new FileInputStream(filePath);
        response.setCharacterEncoding("UTF-8");
        //指明响应的配置信息,包含附件
        response.setHeader("Content-Disposition","attachment; filename="+file);
        //如果文件包含中文名称,需要进行编码转换
        //response.setHeader("Content-Disposition","attachment; filename="+new String(file.getBytes("gb2312"),"ISO-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len= fis.read(buf))!=-1){
            out.write(buf,0,len);
        }
        out.close();
    }

}
  • 测试
http://localhost:8081/download?file=f8acc99d-0d72-4963-a310-ee5c7f0af2d8test1.png
posted @ 2022-04-14 16:27  DogLeftover  阅读(17)  评论(0编辑  收藏  举报