zoukankan      html  css  js  c++  java
  • Java面试题:如何在基于Java的Web项目中实现文件上传和下载?

    [

    在Sevlet 3 以前,Servlet API中没有支持上传功能的API,因此要实现上传功能需要引入第三方工具从POST请求中获得上传的附件或者通过自行处理输入流来获得上传的文件,我们推荐使用Apache的commons-fileupload。
    从Servlet 3开始,文件上传变得无比简单,相信看看下面的例子一切都清楚了。

    上传页面index.jsp:

    <%@ page pageEncoding="utf-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Photo Upload</title>
    </head>
    <body>
    
    <h1>Select your photo and upload</h1>
    
    <hr/>
    
    <div style="color:red;font-size:14px;">${hint}</div>
    
    
    <form action="UploadServlet" method="post" enctype="multipart/form-data">
        Photo file: <input type="file" name="photo" />
        <input type="submit" value="Upload" />
    </form>
    
    </body>
    </html>
    

    支持上传的Servlet:

    package com.jackfrued.servlet;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    @WebServlet("/UploadServlet")
    @MultipartConfig
    public class UploadServlet extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {
            // 可以用request.getPart()方法获得名为photo的上传附件
            // 也可以用request.getParts()获得所有上传附件(多文件上传)
            // 然后通过循环分别处理每一个上传的文件
            Part part = request.getPart("photo");
            if (part != null && part.getSubmittedFileName().length() > 0) {
                // 用ServletContext对象的getRealPath()方法获得上传文件夹的绝对路径
                String savePath = request.getServletContext().getRealPath("/upload");
                // Servlet 3.1规范中可以用Part对象的getSubmittedFileName()方法获得上传的文件名
                // 更好的做法是为上传的文件进行重命名(避免同名文件的相互覆盖)
                part.write(savePath + "/" + part.getSubmittedFileName());
                request.setAttribute("hint", "Upload Successfully!");
            } else {
                request.setAttribute("hint", "Upload failed!");
            }
            // 跳转回到上传页面
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }
    
    }
    
    ]
    转载请保留页面地址:https://www.breakyizhan.com/javamianshiti/2594.html
  • 相关阅读:
    NGINX高并发配置
    一致性哈希算法——PHP实现代码
    TCP三次握手详解
    一致性哈希算法——转载来自张洋
    ngx_http_upstream_keepalive
    高情商人的十一种表现
    Nginx中的upstream轮询机制介绍
    主从读写分离----mysql-proxy0.8.5安装与配置
    分布式事务XA
    微信小程序API
  • 原文地址:https://www.cnblogs.com/breakyizhan/p/13257737.html
Copyright © 2011-2022 走看看