java 如何通过接口的方式实现下载文件?

实现文件下载功能

这里提供了下载的方法,希望能帮到你。

    /**
     * 前端下载文件
     *
     * @param response
     * @param fileName 文件名称
     * @param filePath 文件路径
     */
    public static void download(HttpServletResponse response, String fileName, String filePath) throws Exception {
        BufferedOutputStream bos = null;
        InputStream content = null;
        FileInputStream fileInputStream = null;
        response.reset();
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "*");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/x-download;charset=UTF-8");

            HttpGet http = new HttpGet(filePath);
            CloseableHttpClient httpClient = HttpClients.custom().build();
            CloseableHttpResponse closeableHttpResponse = httpClient.execute(http);

            //获取响应HttpEntity对象
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            response.setHeader("Content-Length", String.valueOf(httpEntity.getContentLength()));
            content = httpEntity.getContent();
            File tempFile = File.createTempFile("byteFile", null);
            FileCopyUtils.copy(StreamUtils.copyToByteArray(content), tempFile);
            fileInputStream = new FileInputStream(tempFile);

            bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = fileInputStream.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } finally {
            if (content != null) {
                content.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java实现文件下载接口的步骤如下: 1. 创建一个Servlet,实现doGet方法。 2. 在doGet方法中获取请求参数,例如文件名。 3. 根据请求参数获取文件路径,例如从服务器的某个目录中获取文件。 4. 设置响应头信息,包括Content-Type和Content-Disposition。 5. 使用ServletOutputStream将文件写出到客户端。 以下是一个简单的示例代码: ```java @WebServlet("/download") public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取请求参数 String filename = request.getParameter("filename"); // 获取文件路径 String filePath = "/path/to/files/" + filename; // 设置响应头信息 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + filename); // 使用ServletOutputStream将文件写出到客户端 try (InputStream inputStream = new FileInputStream(filePath); ServletOutputStream outputStream = response.getOutputStream()) { byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, len); } } } } ``` 在上述示例代码中,我们首先获取请求参数filename,并通过拼接字符串的方式获取到文件的实际路径filePath。然后设置响应头信息,将Content-Type设置为application/octet-stream,表示返回的是二进制流数据;将Content-Disposition设置为attachment,表示文件是以附件形式下载;并设置文件名。最后使用ServletOutputStream将文件写出到客户端。注意,在写出文件之前,需要先将文件读入到InputStream中。为了防止资源泄露,我们使用try-with-resources语句来自动关闭InputStream和ServletOutputStream。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值