Java如何从服务器中下载图片
本文实例为大家分享了Java服务器中下载图片的方法,供大家参考,具体内容如下
importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.net.URL; importjava.net.URLConnection; importorg.apache.commons.io.IOUtils; /** *从服务器中下载图片 * *@paramfileName图片地址 *@paramresponse *@return */ @RequestMapping(value="/download") publicvoiddownloadMedia(HttpServletResponseresponse,HttpServletRequestrequest){ InputStreaminputStream=null; OutputStreamoutputStream=null; try{ //处理中文乱码 request.setCharacterEncoding("UTF-8"); StringfileName=request.getParameter("fileName"); fileName=newString(fileName.getBytes("iso8859-1"),"UTF-8"); //处理浏览器兼容 response.setContentType("application/msexcel;charset=utf-8");//定义输出类型 Enumerationenumeration=request.getHeaders("User-Agent"); StringbrowserName=(String)enumeration.nextElement(); booleanisMSIE=browserName.contains("MSIE"); if(isMSIE){ response.addHeader("Content-Disposition","attachment;fileName="+URLEncoder.encode(fileName,"UTF8")); }else{ response.addHeader("Content-Disposition","attachment;fileName="+newString(fileName.getBytes("gb2312"),"ISO8859-1")); } //url地址如果存在空格,会导致报错!解决方法为:用+或者%20代替url参数中的空格。 fileName=fileName.replace("","%20"); //图片下载 URLurl=newURL(fileName); URLConnectionconn=url.openConnection(); outputStream=response.getOutputStream(); inputStream=conn.getInputStream(); IOUtils.copy(inputStream,outputStream); }catch(IOExceptione){ System.err.println(e); }finally{ IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
以上就是本文的全部内容,希望对大家的学习有所帮助。