起因:
----在我们做文件上传时,通常会保存文件的相对路径在数据库中,然后返回前端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();
}
}
}
}
效果:
当我们路径设置为图片时,浏览器访问结果如下:
当我们路径设置为其他文件时,则为下载:
本次教程到这里就结束了,希望大家多多关注支持(首席摸鱼师 微信同号),持续跟踪最新文章吧~