java实现本地文件转文件流发送到前端
Controller
java
public void export(HttpServletResponse response) {
// 创建file对象
response.setContentType("application/octet-stream");
// 文件名为 s
response.setHeader("Content-Disposition", "attachment;fileName=" + s);
FileUtils.writeBytes(fileName, response.getOutputStream());
}
FileUtils
java
public static void writeBytes(String filePath, OutputStream os) throws IOException{
FileInputStream fis = null;
try
{
File file = new File(filePath);
if (!file.exists())
{
throw new FileNotFoundException(filePath);
}
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int length;
while ((length = fis.read(b)) > 0)
{
os.write(b, 0, length);
}
}
catch (IOException e)
{
throw e;
}
finally
{
IOUtils.close(os);
IOUtils.close(fis);
}
}
如果是临时文件需要删除
controller
java
public void repairStatisticListExport(HttpServletResponse response) {
// 创建file对象
response.setContentType("application/octet-stream");
// 文件名为 s
response.setHeader("Content-Disposition", "attachment;fileName=" + s);
FileUtils.writeBytes(fileName, response.getOutputStream());
FileUtils.deleteFile(fileName);
}
deleteFile方法
java
public static boolean deleteFile(String filePath) {
boolean flag = false;
File file = new File(filePath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
临时文件路径
java
public static String getDefaultBaseDir() {
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("windows")) {
return "C:/uploadPath/";
} else if (os.toLowerCase().startsWith("linux")) {
return "/home/uploadPath/";
}
return "/home/uploadPath/";
}