JAVA根据文件路径在浏览器下载文件

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;

@Slf4j
@RestController
@RequestMapping("/download")
public class DownloadController {

@ApiOperation("下载")
@GetMapping
public void download(HttpServletRequest request, HttpServletResponse response, String path){

    //文件名
    String fileName = path.substring(path.lastIndexOf("/") + 1);
    String contentType = "application/octet-stream";
    try {

        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        long fileLength = new File(path).length();

        response.setContentType(contentType);
        response.setHeader("Content-disposition",
                "attachment; filename=" + new String(fileName.getBytes("utf-8")));
        response.setHeader("Content-Length", String.valueOf(fileLength));

        bis = new BufferedInputStream(new FileInputStream(path));
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();
    } catch (Exception e) {
        log.error("导出文件失败", e);
    }
}

}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java 本身不能直接将文件下载浏览器。通常情况下,Java Web 应用程序会将文件下载到服务器上,然后通过响应头部信息设置浏览器访问该文件的 URL,从而实现浏览器下载文件的功能。 以下是一个简单的示例代码,演示如何将文件下载到服务器并将文件 URL 发送给浏览器: ```java import java.io.*; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.net.URLDecoder; @WebServlet("/download") public class FileDownloader extends HttpServlet { private static final long serialVersionUID = 1L; public FileDownloader() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filePath = URLDecoder.decode(request.getParameter("file"), "UTF-8"); // 获取文件路径 File file = new File(filePath); // 创建文件对象 String fileName = file.getName(); // 获取文件名 if (file.exists()) { response.setContentType("application/octet-stream"); // 设置响应内容类型 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // 设置响应头部信息,告诉浏览器打开“文件下载”对话框并设置文件名 InputStream inputStream = new FileInputStream(file); // 创建文件输入流 OutputStream outputStream = response.getOutputStream(); // 创建响应输出流 byte[] buffer = new byte[4096]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); // 将文件内容写入响应输出流 } inputStream.close(); outputStream.flush(); outputStream.close(); } else { response.setContentType("text/html;charset=UTF-8"); // 设置响应内容类型 response.getWriter().println("文件不存在!"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 在上面的示例中,`doGet` 方法通过 URL 参数获取文件路径,创建一个文件对象,并设置响应头部信息。然后,通过文件输入流读取文件内容并将其写入响应输出流,最后刷新并关闭输出流,实现文件下载的功能。如果文件不存在,将返回一个错误信息。 在响应头部信息中,设置 `Content-Disposition` 为 `attachment`,表示将该文件作为附件下载浏览器会弹出“文件下载”对话框。设置 `filename` 参数为文件名,告诉浏览器文件的名称。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值