java主方法如何处理文件上传下载

发布时间:2024-12-06 11:31:58 作者:小樊
来源:亿速云 阅读:79

在Java中,可以使用多种方法处理文件上传和下载。这里,我将向您展示如何使用Java Servlet来处理文件上传和下载。

  1. 文件上传

首先,创建一个HTML表单,用于选择要上传的文件:

<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <form action="FileUploadServlet" method="post" enctype="multipart/form-data">
        Select file to upload:
        <input type="file" name="file" id="file">
        <br><br>
        <input type="submit" value="Upload">
    </form>
</body>
</html>

接下来,创建一个名为FileUploadServlet的Java Servlet,用于处理文件上传:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FileUploadServlet extends HttpServlet {
    private static final String UPLOAD_DIRECTORY = "uploads";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part filePart = request.getPart("file");
        String fileName = getSubmittedFileName(filePart);
        InputStream fileContent = filePart.getInputStream();

        saveFile(fileName, fileContent);

        response.sendRedirect("success.html");
    }

    private String getSubmittedFileName(Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

    private void saveFile(String fileName, InputStream fileContent) throws IOException {
        File uploadDir = new File(getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }

        try (FileOutputStream fos = new FileOutputStream(new File(uploadDir, fileName))) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileContent.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }
}
  1. 文件下载

创建一个名为FileDownloadServlet的Java Servlet,用于处理文件下载:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FileDownloadServlet extends HttpServlet {
    private static final String FILE_DIRECTORY = "uploads";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName = request.getParameter("fileName");
        File file = new File(getServletContext().getRealPath("") + File.separator + FILE_DIRECTORY, fileName);

        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            try (FileInputStream fis = new FileInputStream(file)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

现在,您可以在Web应用程序中使用这两个Servlet来处理文件上传和下载。请确保在web.xml中配置这两个Servlet,以便它们可以正确处理请求。

推荐阅读:
  1. SpringBoot,SpringCloud项目实战视频高并发高性能分布式框架从无到有微服务架构设计
  2. 还不清楚HashMap吗?读完这篇你就懂了!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:如何在java主方法中使用文件IO流

下一篇:怎样在java主方法中实现文件压缩解压

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》