java 下载图片到本地文件夹
不多说 直接上代码
String imgurl = request.getParameter("imgurl"); //图片url地址
String name = request.getParameter("name"); //保存的图片名称
HttpURLConnection conn = null;
InputStream inputStream = null;
BufferedInputStream bis = null;
FileOutputStream out = null;
try
{
File file0=new File("C:\\Users\\Administrator\\Desktop");
if(!file0.isDirectory()&&!file0.exists()){
file0.mkdirs();
}
out = new FileOutputStream(file0+"\\"+name+".png");
// 建立链接
URL httpUrl=new URL(imgurl);
conn=(HttpURLConnection) httpUrl.openConnection();
//以Post方式提交表单,默认get方式
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
// post方式不能使用缓存
conn.setUseCaches(false);
//连接指定的资源
conn.connect();
//获取网络输入流
inputStream=conn.getInputStream();
bis = new BufferedInputStream(inputStream);
byte b [] = new byte[1024];
int len = 0;
while((len=bis.read(b))!=-1){
out.write(b, 0, len);
}
response.getWriter().write(Globals.SUCCESS);
} catch (Exception e) {
e.printStackTrace();
response.getWriter().write(Globals.SYSTEM_BUSY);
}finally{
try {
if(out!=null){
out.close();
}
if(bis!=null){
bis.close();
}
if(inputStream!=null){
inputStream.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}