• 上传和下载文件


    下载文件

    编写一个Servlet用于处理文件下载

    1. @WebServlet("/file")
    2. public class FileServlet extends HttpServlet {
    3. @Override
    4. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    5. resp.setContentType("image/png");
    6. OutputStream outputStream = resp.getOutputStream();
    7. InputStream inputStream = Resources.getResourceAsStream("icon.png");
    8. }
    9. }

    引入IO一个工具库

    1. <dependency>
    2. <groupId>commons-iogroupId>
    3. <artifactId>commons-ioartifactId>
    4. <version>2.6version>
    5. dependency>

    使用此类库可以快速完成IO操作:

    1. resp.setContentType("image/png");
    2. OutputStream outputStream = resp.getOutputStream();
    3. InputStream inputStream = Resources.getResourceAsStream("icon.png");
    4. //直接使用copy方法完成转换
    5. IOUtils.copy(inputStream, outputStream);

    在前端页面添加一个链接,用于下载此文件

    1. <hr>
    2. <a href="file" download="icon.png">点我下载高清资源a>

    上传文件

    前端编写

    注意必须添加`enctype="multipart/form-data"`,来表示此表单用于文件传输。

    1. <form method="post" action="file" enctype="multipart/form-data">
    2. <div>
    3. <input type="file" name="test-file">
    4. div>
    5. <div>
    6. <button>上传文件button>
    7. div>
    8. form>

    编写一下Servlet代码

    必须添加`@MultipartConfig`注解来表示此Servlet用于处理文件上传请求

    1. @MultipartConfig//表示用于文件传输
    2. @WebServlet("/file")
    3. public class FileServlet extends HttpServlet {
    4. @Override
    5. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    6. try(FileOutputStream stream = new FileOutputStream("(推荐绝对路径)/Users/nagocoler/Documents/IdeaProjects/WebTest/test.png")){
    7. Part part = req.getPart("test-file");(表单名称)
    8. IOUtils.copy(part.getInputStream(), stream);
    9. resp.setContentType("text/html;charset=UTF-8");
    10. resp.getWriter().write("文件上传成功!");
    11. }
    12. }
    13. }

  • 相关阅读:
    Python gRPC ALTS 身份验证
    unity Holoens2开发,使用Vuforia识别实体或图片 触发交互
    linux manual
    若依多租户集成浅析(基于数据源隔离)
    使用结构体组织相关联的数据(5)
    数据可视化项目(一)
    window查看/修改目录权限:icacls命令
    机器学习day4
    微信小程序运行机制和生命周期
    契约测试理论篇
  • 原文地址:https://blog.csdn.net/weixin_51992178/article/details/126685889