起因:
----在我們做文件上傳時,通常會保存文件的相對路徑在數(shù)據(jù)庫中,然后返回前端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("文件不存在");
}
// 設(shè)置響應類型
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();
}
}
}
}
效果:
當我們路徑設(shè)置為圖片時,瀏覽器訪問結(jié)果如下:
當我們路徑設(shè)置為其他文件時,則為下載:
文章來源:http://www.zghlxwxcb.cn/news/detail-774016.html
本次教程到這里就結(jié)束了,希望大家多多關(guān)注支持(首席摸魚師 微信同號),持續(xù)跟蹤最新文章吧~文章來源地址http://www.zghlxwxcb.cn/news/detail-774016.html
到了這里,關(guān)于Java教程:如何讀取服務(wù)器文件并推送到前端并下載,圖片格式以瀏覽器渲染模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!