日期:2014-05-17  浏览次数:20754 次

io 文件下载方法
现在这个下载方法能够下载这种路径:E:\Tomcat-1\webapps\duoduoasp\upload\file\201403\111.pdf
但是我现在上传的文件是这种路径:http://localhost:1111/duoduoasp/upload/image/201403/111.jpg
这个方法就解析不了文件了,有没有办法把http://的路径改为第一种路径呢?新手求大神帮助~~
/**
 * 下载
 */
@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是不必要的
}