根据URL下载图片至客户端、服务器的简单实例
1、保存至服务器
根据路径保存至项目所在服务器上。
StringimgUrl="";//图片地址
try{
//构造URL
URLurl=newURL(imgUrl);
//打开连接
URLConnectioncon=url.openConnection();
//输入流
InputStreamis=con.getInputStream();
//1K的数据缓冲
byte[]bs=newbyte[1024];
//读取到的数据长度
intlen;
//输出的文件流
OutputStreamos=newFileOutputStream("c:\\image.jpg");//保存路径
//开始读取
while((len=is.read(bs))!=-1){
os.write(bs,0,len);
}
//完毕,关闭所有链接
os.close();
is.close();
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
2、保存至本地
以浏览器下载的方式保存至本地。
StringimgUrl="";//URL地址
StringfileName=imgUrl.substring(imgUrl.lastIndexOf('/')+1);
BufferedInputStreamis=null;
BufferedOutputStreamos=null;
try{
URLurl=newURL(imgUrl);
this.getServletResponse().setContentType("application/x-msdownload;");
this.getServletResponse().setHeader("Content-disposition","attachment;filename="+newString(fileName.getBytes("utf-8"),"ISO8859-1"));
this.getServletResponse().setHeader("Content-Length",String.valueOf(url.openConnection().getContentLength()));
is=newBufferedInputStream(url.openStream());
os=newBufferedOutputStream(this.getServletResponse().getOutputStream());
byte[]buff=newbyte[2048];
intbytesRead;
while(-1!=(bytesRead=is.read(buff,0,buff.length))){
os.write(buff,0,bytesRead);
}
if(is!=null)
is.close();
if(os!=null)
os.close();
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
以上这篇根据URL下载图片至客户端、服务器的简单实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。