java文件上传下载功能实现代码

Java文件上传下载是Web开发中常见的功能,实现代码一般基于Servlet或Spring MVC等框架。下面是实现Java文件上传下载功能的完整攻略,包含示例代码。

Java文件上传下载是Web开发中常见的功能,实现代码一般基于Servlet或Spring MVC等框架。下面是实现Java文件上传下载功能的完整攻略,包含示例代码。

1. 文件上传

Java文件上传一般需要使用表单提交,数据由客户端通过HTTP POST请求发送到服务器。客户端可以使用HTML表单或JavaScript+FormData等方式实现。服务端接收到数据后,可以使用Java I/O流等方式将文件保存到指定目录。

1.1 HTML表单方式上传文件

HTML表单中通过元素实现文件选择功能,提交表单时,浏览器会将文件数据包装成multipart/form-data编码格式,发送到服务器。服务端接收到表单提交的数据后,通过request.getParameter()方法无法获取文件数据,需要通过request.getPart()方法获取文件Part对象,进一步操作。

示例代码:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>文件上传HTML表单</title>
</head>
<body>
    <form action="fileUploadServlet" method="post" enctype="multipart/form-data">
        <label for="file">选择文件:</label>
        <input type="file" name="file" id="file" /><br />
        <input type="submit" value="上传" />
    </form>
</body>
</html>
@WebServlet("/fileUploadServlet")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        Part filePart = request.getPart("file"); // 获取文件Part对象
        String fileName = filePart.getSubmittedFileName(); // 获取文件名
        InputStream fileContent = filePart.getInputStream(); // 获取文件输入流

        String uploadPath = request.getServletContext().getRealPath("/uploads"); // 上传文件保存目录
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        File savedFile = new File(uploadDir, fileName);
        try(BufferedInputStream bis = new BufferedInputStream(fileContent);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));) {
            byte[] buffer = new byte[1024];
            int len;
            while((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        }

        response.getWriter().println("文件上传成功!");
    }
}

1.2 JavaScript+FormData方式上传文件

JavaScript+FormData方式上传文件相对于HTML表单方式具有更好的兼容性和灵活性。通过FormData对象将表单数据提交到服务器,能够同时上传多个文件和其他数据。

示例代码:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>文件上传JavaScript方式</title>
</head>
<body>
    <input type="file" id="file" /><br />
    <button onclick="uploadFile()">上传</button>
    <script>
        function uploadFile() {
            var files = document.getElementById('file').files;
            var formData = new FormData();
            for(var i = 0; i < files.length; i++) {
                formData.append('file', files[i]);
            }
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            }
            xhr.open('POST', 'fileUploadServlet', true);
            xhr.send(formData);
        }
    </script>
</body>
</html>
@WebServlet("/fileUploadServlet")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        Collection<Part> fileParts = request.getParts(); // 获取所有上传文件Part对象
        String uploadPath = request.getServletContext().getRealPath("/uploads"); // 上传文件保存目录
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
        for (Part filePart : fileParts) {
            if (filePart.getSubmittedFileName() == null) {
                continue; // 忽略非文件Part对象
            }
            String fileName = filePart.getSubmittedFileName(); // 获取文件名
            InputStream fileContent = filePart.getInputStream(); // 获取文件输入流
            File savedFile = new File(uploadDir, fileName);
            try (BufferedInputStream bis = new BufferedInputStream(fileContent);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savedFile));) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
            }
            response.getWriter().println("文件" + fileName + "上传成功!<br />");
        }
    }
}

2. 文件下载

Java文件下载一般需要使用HTTP响应方式实现,客户端通过链接、按钮等方式发送下载请求。服务端将文件数据以application/octet-stream或特定格式的MIME类型形式发送到客户端,客户端会根据响应头中的Content-Disposition属性将文件保存到本地。

2.1 通过Servlet实现文件下载

使用Servlet实现文件下载相对于普通的HTTP服务器具有更好的可定制性和扩展性。可以通过Servlet过滤器或权限控制等方式增加安全性。

示例代码:

@WebServlet("/fileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=file.txt");

        String filePath = getServletContext().getRealPath("/downloads"); // 下载文件路径
        File downloadFile = new File(filePath, "file.txt");
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downloadFile));
                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
        }
    }
}

2.2 通过SpringMVC实现文件下载

使用SpringMVC框架相对于Servlet更加简洁便捷。可以通过ResponseEntity类型返回文件数据及响应头信息。

示例代码:

@GetMapping("/fileDownload")
public ResponseEntity<byte[]> fileDownload() throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", "file.txt");

    String filePath = servletContext.getRealPath("/downloads"); // 下载文件路径
    File downloadFile = new File(filePath, "file.txt");
    byte[] data = Files.readAllBytes(downloadFile.toPath());

    return new ResponseEntity<byte[]>(data, headers, HttpStatus.OK);
}

本文标题为:java文件上传下载功能实现代码

基础教程推荐