用Java IO流读取本地文件,并在前端显示

本文介绍了一种使用Java Web技术从服务器读取图片并将其作为响应返回的方法。通过@RequestMapping注解映射请求,利用FileInputStream读取本地图片文件,并通过ServletOutputStream将图片数据输出到客户端。

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

@RequestMapping(value = "readImg")
    public String readImg(HttpServletRequest request,HttpServletResponse response) throws IOException {
        
        ServletOutputStream out = null;  
        FileInputStream ips = null;  
        String url = "D:/one/two.png";
        try {  
            //获取图片存放路径 
            File file = new File(url);
            if(!file.exists()) {
                return null;
            }
            
            ips = new FileInputStream(file);  
            response.setContentType("multipart/form-data");  
            out = response.getOutputStream();  
            //读取文件流  
            int len = 0;  
            byte[] buffer = new byte[1024 * 10];  
            while ((len = ips.read(buffer)) != -1){  
                out.write(buffer,0,len);  
            }  
            out.flush();  
        }catch (Exception e){  
            e.printStackTrace();  
        }finally {  
            out.close();  
            ips.close();  
        }  
        return null; 

    }

最后在图片路径中加入即可

你可以使用Java提供的File和Scanner类来读取本地HTML文件,然后将读取到的内容返回给前端。以下是一个示例代码: ```java import java.io.File; import java.io.IOException; import java.util.Scanner; public class HtmlReader { public static String readHtmlFile(String filePath) throws IOException { StringBuilder contentBuilder = new StringBuilder(); File file = new File(filePath); try (Scanner scanner = new Scanner(file)) { while (scanner.hasNextLine()) { String line = scanner.nextLine(); contentBuilder.append(line).append("\n"); } } return contentBuilder.toString(); } } ``` 在你的Web应用程序中,你可以将此方法用于读取HTML文件将其返回给前端: ```java import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/html") public class HtmlController { @GetMapping @ResponseBody public String getHtml(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileName) throws IOException { String filePath = request.getServletContext().getRealPath("/WEB-INF/html/" + fileName); return HtmlReader.readHtmlFile(filePath); } } ``` 在上面的代码中,我们通过@RequestParam注释从请求参数中获取HTML文件名,然后将其传递给HtmlReader.readHtmlFile()方法来读取文件返回其内容。最后,我们使用@ResponseBody注释将内容作为响应主体返回给前端。注意,这里的文件路径使用了相对路径,我们假设HTML文件存储在Web应用程序的/WEB-INF/html目录中。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值