java读取文件并返回前端

该博客内容展示了如何在Spring Boot应用中实现文件的下载。提供了两个方法,一个用于以附件形式下载word文档,另一个则以文本形式直接在浏览器中显示txt文件。主要涉及的技术包括HttpServletResponse的使用、文件流处理及编码设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.demo.controller;

import org.apache.commons.io.Charsets;
import org.apache.commons.io.FileUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("file")
public class TestController {

    @GetMapping(value = "/test1")
    public void test(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        // 设置编码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
        String path = "D://logs/" + fileName;
        try {
            FileInputStream in = new FileInputStream(new File(path));
            FileCopyUtils.copy(in, response.getOutputStream());
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在")
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("download")
    public void  download(String filename, HttpServletResponse res) throws IOException {
        String path = "D://logs/"+filename;
        res.setCharacterEncoding("UTF-8");
        // attachment是以附件的形式下载,inline是浏览器打开
        res.setHeader("Content-Disposition", "inline;filename="+filename+".txt");
        res.setContentType("text/plain;UTF-8");
        // 把二进制流放入到响应体中
        ServletOutputStream os = res.getOutputStream();
        File file = new File(path);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值