获取文件流
GridFSDBFile file = mongoFileUtil.getFileByFileID(azMongoTemplate, documentData.getFileId(), collectName);
InputStream isr = file.getInputStream();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = isr.read(buffer)) != -1) {
swapStream.write(buffer, 0, len);
}
isr.close();
return swapStream;
} catch (Exception e) {
}
控制器
OutputStream outputStream = null;
byte[] buffer = azReportPullService.getMongoDBFile(param).toByteArray();
try {
if (null != buffer && buffer.length > 0) {
response.reset();
String fileName=param.getFileName().
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(.getBytes("GBK"), "ISO8859_1"));
//前后端分离要加这个识别文件名
response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
response.addHeader("Content-Length", "" + buffer.length);
outputStream = response.getOutputStream();
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
测试直接浏览器打开路径。
附带IO流转化
public class ConvertUtil {
//inputStream转outputStream
public ByteArrayOutputStream parse(InputStream in) throws Exception
{
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) != -1) {
swapStream.write(ch);
}
return swapStream;
}
//outputStream转inputStream
public ByteArrayInputStream parse(OutputStream out) throws Exception
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
baos=(ByteArrayOutputStream) out;
ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
return swapStream;
}
//inputStream转String
public String parse_String(InputStream in) throws Exception
{
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) != -1) {
swapStream.write(ch);
}
return swapStream.toString();
}
//OutputStream 转String
public String parse_String(OutputStream out)throws Exception
{
ByteArrayOutputStream baos=new ByteArrayOutputStream();
baos=(ByteArrayOutputStream) out;
ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
return swapStream.toString();
}
//String转inputStream
public ByteArrayInputStream parse_inputStream(String in)throws Exception
{
ByteArrayInputStream input=new ByteArrayInputStream(in.getBytes());
return input;
}
//String 转outputStream
public ByteArrayOutputStream parse_outputStream(String in)throws Exception
{
return parse(parse_inputStream(in));
}
}