Java读取第三方接口文件流返回前端预览、或保存文件
第三方接口文件流
·
Java读取第三方接口文件流返回前端预览
第三方接口返回文件流,将文件流返回我们应用前端实现预览文件功能
package com.example.demo;
import cn.hutool.core.util.IdUtil;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import static org.apache.catalina.manager.Constants.CHARSET;
@RestController
@RequestMapping("file")
public class TestController {
/**
* 前端下载文件
* @param response
* @throws UnsupportedEncodingException
*/
@GetMapping(value = "/test1")
public void test(HttpServletResponse response) throws UnsupportedEncodingException {
// 设置编码
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("test.pdf", "UTF-8"));
String path = "D://test.pdf";
try {
FileInputStream in = new FileInputStream(new File(path));
FileCopyUtils.copy(in, response.getOutputStream());
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 前端预览文件
* @param response
* @throws IOException
*/
@RequestMapping("download")
public void download(HttpServletResponse response) throws IOException {
String filePath = "D:\\test.pdf";
System.out.println("filePath:" + filePath);
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] bs = new byte[1024];
int len = 0;
response.reset(); // 非常重要
URL u = new URL("file:///" + filePath);
String contentType = u.openConnection().getContentType();
response.setContentType(contentType);
response.setHeader("Content-Disposition", "inline;filename="
+ "test.pdf");
// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
OutputStream out = response.getOutputStream();
while ((len = br.read(bs)) > 0) {
out.write(bs, 0, len);
}
out.flush();
out.close();
br.close();
}
/**
* 调用第三方流接口, 将文件保存到本地、读取本地文件返回前端预览
* @param response
* @throws IOException
*/
@RequestMapping("test2")
public void test2(HttpServletResponse response) throws IOException {
HttpURLConnection urlConnection = null;
FileOutputStream fileOutputStream;
InputStream inputStream;
String fileName = IdUtil.nanoId();
try {
URL url = new URL("http://localhost:8080/file/download");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(20000);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=" + CHARSET);
urlConnection.connect();
File file = new File("D://"+fileName+".pdf");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
fileOutputStream = new FileOutputStream("D://"+fileName+".pdf");
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
byte[] buf = new byte[4096];
int length = bufferedInputStream.read(buf);
while (-1 != length) {
bufferedOutputStream.write(buf, 0, length);
length = bufferedInputStream.read(buf);
}
bufferedInputStream.close();
bufferedOutputStream.close();
} catch (Exception e) {
System.out.println("getFile error: " + e);
} finally {
if (null != urlConnection) {
urlConnection.disconnect();
}
}
String filePath = "D://"+fileName+".pdf";
File f = new File("D://"+fileName+".pdf");
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] bs = new byte[1024];
int len = 0;
response.reset(); // 非常重要
URL u = new URL("file:///" + filePath);
String contentType = u.openConnection().getContentType();
response.setContentType(contentType);
response.setHeader("Content-Disposition", "inline;filename="
+ fileName + ".pdf");
// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
OutputStream out = response.getOutputStream();
while ((len = br.read(bs)) > 0) {
out.write(bs, 0, len);
}
out.flush();
out.close();
br.close();
}
/**
* 调用第三方流接口, 将文件流返回前端预览
* @param request
* @param response
*/
@RequestMapping("test3")
public void test3(HttpServletRequest request, HttpServletResponse response) {
HttpURLConnection urlConnection = null;
InputStream inputStream;
try {
URL url = new URL("http://localhost:8080/file/download");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(20000);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=" + CHARSET);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
byte[] buf = new byte[4096];
int length = bufferedInputStream.read(buf);
ServletOutputStream out = response.getOutputStream();
while (-1 != length) {
out.write(buf, 0,length);
length = bufferedInputStream.read(buf);
}
out.flush();
out.close();
bufferedInputStream.close();
} catch (Exception e) {
System.out.println("getFile error: " + e);
} finally {
if (null != urlConnection) {
urlConnection.disconnect();
}
}
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)