• 上传和下载文件


    下载文件

    编写一个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. }

  • 相关阅读:
    计算机视觉与深度学习-经典网络解析-ZFNet-[北邮鲁鹏]
    livoxhapsdk2
    数字化外协生产综合管理系统,实现信息自动同步,数据自动统计分析!
    Python多线程与多进程
    Spring中PointcutAdvisor和IntroductionAdvisor梳理
    Mac上使用Charles抓包
    java写的教师信息管理系统代码
    Qt | Qt For Android、Qt5.14.2安卓开发环境搭建详细步骤
    python基础语法回顾
    CentOS7安装Oracle数据库的全流程
  • 原文地址:https://blog.csdn.net/weixin_51992178/article/details/126685889