Java教程:如何读取服务器文件并推送到前端并下载,图片格式以浏览器渲染模式

该文章介绍了如何在Java后端使用文件输入输出流处理文件,避免直接提供文件访问地址给前端。通过示例代码展示了如何根据文件类型设置响应头,实现图片的浏览器预览和文件的安全下载功能。
摘要由CSDN通过智能技术生成

起因:

----在我们做文件上传时,通常会保存文件的相对路径在数据库中,然后返回前端http访问路径,来对文件进行下载或图片预览功能,但是有时候我们并不想直接返回文件访问地址给前端,这就用到了Java当中的文件输入输出流,将文件以流的方式响应给浏览器,并渲染出图片或下载,接下来就列出具体代码,供大家使用

Java后端代码:

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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 文件流-Controller
 */
@Slf4j
@RestController
@RequestMapping("/fileStream")
public class FileStreamController {

    /**
     * 获取文件流
     *
     * @param fileAddress 文件地址
     * @return
     */
    @GetMapping("/getFileStream")
    public void getFileStream(@RequestParam("fileAddress") String fileAddress, HttpServletResponse response) {
        File file = new File("文件路径");
        if (!file.isFile()) {
            throw new RuntimeException("文件不存在");
        }

        // 设置响应类型
        if ("jpg/jpeg/png/bmp/gif/tif/icon/ico".contains(file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase())) {
            response.setContentType("text/html; charset=UTF-8");
            response.setContentType("image/jpeg");
        } else {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        }

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(file);
            outputStream = new BufferedOutputStream(response.getOutputStream());

            byte[] buffer = new byte[1024];
            while (true) {
                int len = inputStream.read(buffer);
                if (len == -1) {
                    break;
                }
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (Exception e) {
            log.error("文件读取异常,原因:{}", e.toString());
            throw new RuntimeException("文件读取异常");
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

效果:

当我们路径设置为图片时,浏览器访问结果如下:

在这里插入图片描述

当我们路径设置为其他文件时,则为下载:

在这里插入图片描述

本次教程到这里就结束了,希望大家多多关注支持(首席摸鱼师 微信同号),持续跟踪最新文章吧~

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值