//写入文件到response流中 -----网站上文件下载
public static void writeFileToResponse(HttpServletRequest req, HttpServletResponse httpResponse, String fileId,
throws Exception
{
FileInputStream fis = null;
OutputStream os = null;
try
{
if(logger.isDebugEnabled())
{
logger.debug("download file path:" + file.getAbsolutePath());
}
Long fileLength = file.length();
if (fileLength <= Integer.MAX_VALUE)
{
IOUtils.setContentLength(req, httpResponse, fileLength);
}
fis = new FileInputStream(file);
IOUtils.skip(req, fis);
byte b[] = new byte[1024];
int j = -1;
os = httpResponse.getOutputStream();
while ((j = fis.read(b)) != -1)
{
os.write(b, 0, j);
os.flush();
}
}
catch (FileNotFoundException e)
{
logger.error(" download Error: could not find file!", e);
throw new Exception(ICommonResultCode.INVALID_PARAMETER + "", "request param fileid " + fileId
+ " can't find the file " + file.getAbsolutePath());
}
catch (IOException e)
{
logger.error("download Error: could not download the file " + file.getAbsolutePath()
+ ", may be net is unsteadiness!", e);
throw new Exception(ICommonResultCode.NET_ERROR + "", "could not download the file "
+ file.getAbsolutePath() + ", may be net is unsteadiness!");
}
finally
{
try
{
if (fis != null)
{
fis.close();
}
}
catch (IOException e)
{
fis = null;
}
}
}