JavaWeb实现文件的上传和下载

前期准备

jar包准备

用到两个jar包

  • 1.javaee-api-7.0.jar
  • 2.smartupload.jar

第一个相信大家都明白,在用到Servlet写后端的时候都会需要。
第二个则类似于与IO相关的工具类。

网页界面

这里仅仅为了实现功能,以最基础的表单为例:

提交界面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Files Download</title>
  </head>
  <body>
  <form action="/uploadtest" method="post" enctype="multipart/form-data" >
    选择图片:<input type="file" name="pic"><br>
    输入:<input type="text" name="input"><br>
    <input type="submit">
  </form>
  </body>
</html>

提交成功页

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<img src="uploadfiles/${filename}">
<a href="downimg?filename=${filename}">下载</a>
</body>
</html>

文件上传

文件上传指的是客户端向服务器上传文件,即将保存在客户端的文件上传至服务器中的一个副本,保存到服务器中。

@WebServlet(urlPatterns = "/uploadtest")
public class UpLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            //1、创建上传文件对象
            SmartUpload smartUpload = new SmartUpload();
            //2、初始化上传操作
            PageContext pageContext = JspFactory.getDefaultFactory()
                    .getPageContext(this,req,resp,null,false,1024,true);
            smartUpload.initialize(pageContext);
            //2.1、设置编码
            smartUpload.setCharset("utf-8");
            //3、上传
            smartUpload.upload();
            //4、获取文件信息
            File file =smartUpload.getFiles().getFile(0);
            String fileName=file.getFileName();
            String contentType=file.getContentType();
            //4.1、获取文本信息
            String text=smartUpload.getRequest().getParameter("input");
            System.out.println(text);
            //5、指定上传的路径
            String uploadPath = "/uploadfiles/"+fileName;
            //6、保存到指定位置
            file.saveAs(uploadPath,File.SAVEAS_VIRTUAL);
            //7、跳转到成功页面
            req.setAttribute("filename",fileName);
            req.getRequestDispatcher("success.jsp").forward(req,resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}

文件下载

文件下载指的是客户端从服务器下载文件,即将原来保存在服务器中的文件下载到客户端中一个副本保存。

@WebServlet(urlPatterns = "/downimg")
public class DownLoadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename=req.getParameter("filename");
        String path="/uploadfiles/"+filename;
        //设置响应头信息和头类型
        resp.setContentType("application/octet-stream");
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));
        //跳转页面
        req.getRequestDispatcher(path).forward(req,resp);
        //清空缓冲区
        resp.flushBuffer();
    }
}

补充

整体结构

在这里插入图片描述

获取文字

此时如果表单中有其他数据时,不能通过request直接获取,需要通过SmartUpload对象获取

 String name=su.getRequest().getParameter("bookName");

并且该代码要在SmartUpload操作完成后添加

解决乱码

new String(name.getBytes("GBK"),"utf-8")

getPageContext

PageContext pageContext = JspFactory.getDefaultFactory()
                    .getPageContext(Servlet servlet,
                    ServletRequest request,
                    ServletResponse response,
                    String errorPageURL,
                    boolean needsSession,
                    int buffer,
                    boolean autoflush);
参数含义
servlet请求的servlet,在servlet中传this即可
requestservlet上挂起的当前请求
responseservlet上挂起的当前响应
errorPageURL请求JSP的错误页面的URL,或null
needsSSession是否需要session
buffer以字节为单位的缓冲区大小
autoflush缓冲区应该在缓冲区溢出时自动刷新到输出流,还是抛出IOException

smartupload常用方法

属性名称说明
public final void initialize(PageContext pageContext)执行上传和下载的初始化工作,必须实现
public void upload()实现文件数据的上传,在 initialize方法后执行
public int save(String pathName)将全部上传文件保存到指定的目录下,并返回保存的文件个数
public void setAllowFilesList(String ExtList)指定允许上传的文件扩展名,接受一个扩展名列表,以逗号分割
public void setDeniedFilesList(String fileList)指定了禁止上传的文件拓展名列表,每个拓展名之间以逗号分割
public void setMaxFileSize(long filesize)设定每个文件允许上传的最大长度
public void setTotalMaxFileSize(long totalfilesize)设定允许上传文件的总长度
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
文件上传下载是Web应用程序中常见的功能之一,下面给出一个简单的JavaWeb实现: 1. 文件上传JSP页面中,需要一个表单,用于选择文件并提交: ```html <form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="Upload"> </form> ``` 在Servlet中,处理文件上传的代码如下: ```java protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取上传文件 Part filePart = request.getPart("file"); String fileName = getFileName(filePart); // 保存上传文件 OutputStream out = new FileOutputStream(new File("D:/uploads/" + fileName)); InputStream in = filePart.getInputStream(); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); // 返回上传成功的信息 response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); writer.println("上传成功!"); } // 获取上传文件名 private String getFileName(Part part) { String contentDisposition = part.getHeader("content-disposition"); String[] tokens = contentDisposition.split(";"); for (String token : tokens) { if (token.trim().startsWith("filename")) { return token.substring(token.indexOf("=") + 2, token.length() - 1); } } return ""; } ``` 2. 文件下载JSP页面中,需要一个超链接,用于触发文件下载: ```html <a href="download?fileName=test.txt">Download</a> ``` 在Servlet中,处理文件下载的代码如下: ```java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取要下载文件名 String fileName = request.getParameter("fileName"); // 设置响应头,告诉浏览器下载文件 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1")); // 读取要下载文件并写入响应流 InputStream in = new FileInputStream(new File("D:/uploads/" + fileName)); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int length = -1; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.close(); } ``` 以上就是JavaWeb实现文件上传下载的简单示例,需要注意的是上传文件保存在服务器的硬盘上,因此需要确保上传文件不会对服务器造成安全威胁,如上传病毒文件、木马等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值