java实现本地文件转文件流发送到前端
Controller
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
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
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方法文章来源:https://www.toymoban.com/news/detail-689314.html
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;
}
临时文件路径文章来源地址https://www.toymoban.com/news/detail-689314.html
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/";
}
到了这里,关于java实现本地文件转文件流发送到前端的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!