日期:2014-05-17 浏览次数:20820 次
/**
* 下载
*/
@RequestMapping(value={"/download"}, method={RequestMethod.GET})
@ResponseBody
public void download(Long shippingFaceId, HttpServletRequest request, HttpServletResponse response) {
ShippingFace shippingFace = shippingFaceService.find(shippingFaceId);
String filename = (shippingFace.getSn());
filename = WebUtils.encodeChineseDownloadFileName(request, filename);
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ";");
String filePath = shippingFace.getFile();
File file = new File(filePath);
BufferedInputStream in = null;
ServletOutputStream os = null;
try {
os = response.getOutputStream();
in = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
IOUtils.write(out.toByteArray(), os);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(os);
}
}
String filePath = "";
if(StringUtils.hasText(filePath)){ //使用Spring的StringUtils判断字符串是否为null或空
InputStream inputStream = null;
if(filePath.startsWith("http")){
inputStream = new URL(filePath).openStream();
}else{
File file = new File(filePath);
if(!file.exists()
------解决方案--------------------
file.isDirectory()){
throw new IOException(filePath + "文件不存在!");
}
if(file.isDirectory()){
throw new IOException(filePath + "是一个目录");
}
inputStream = new FileInputStream(file);
}
//可以使用Spring的FileCopyUtils来拷贝流,而且它会自动帮你关闭掉
FileCopyUtils.copy(inputStream, response.getOutputStream());
//IOUtils也有copy(InputStream input, OutputStream output)
//所以你原来代码中的ByteArrayOutputStream是不必要的
}