大神们,请教一个问题,如何中转网络文件?
比如说一个网络文件,在我的页面上提供下载入口(这个网络文件的下载地址),点击下载即可下载这个网络文件,但来源显示的是我的域名,不是网络文件原本的域名,也就是说我这里是中转,并非下载到我的服务器,是提供给别人下载(让人感觉来源是我这,而非其他网络上)
我尝试了先读取网络文件的数据流,然后再写出去。这个方法对网络文件比较小的可以实现,但对大的文件,就会消耗在读取文件流,卡住了。。下面是代码,求大神救助
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 附件下载
*/
public void downloadTaxpayer(HttpServletRequest request,HttpServletResponse response,String path){
response.reset();//可以加也可以不加
response.setContentType("application/x-download");//设置为下载application/x-download
OutputStream output = null;
//FileInputStream bis = null;
BufferedInputStream bis = null;
File file = null;
try{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组 ========================这个位置读取大文件就会卡住了。
byte[] getData = readInputStream(inputStream);
// 取得文件的后缀名。
String filenamedisplay = path.substring(path.lastIndexOf("/") + 1).toUpperCase();
file=new File(request.getSession().getServletContext().getRealPath("/")+"/pages/"+filenamedisplay);
filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8");
response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay);
FileOutputStream os = new FileOutputStream(file);
os.write(getData);
os.close();
os = null;
byte[] b = new byte[1024*512];
output = response.getOutputStream();
InputStream is = new FileInputStream(file);
bis = new BufferedInputStream(is);
int i = 0;
while((i = bis.read(b)) > 0){
output.write(b, 0, i);
}
output.flush();
}catch (Exception e){
e.printStackTrace();
}
finally{
if(bis != null){
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bis = null;
}
if(output != null){
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
output = null;
}
file.delete();
}
}