Java如何从服务器中下载图片
程序员文章站
2024-03-11 15:52:55
本文实例为大家分享了java服务器中下载图片的方法,供大家参考,具体内容如下
import java.io.ioexception;
import java....
本文实例为大家分享了java服务器中下载图片的方法,供大家参考,具体内容如下
import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.net.url; import java.net.urlconnection; import org.apache.commons.io.ioutils; /** * 从服务器中下载图片 * * @param filename 图片地址 * @param response * @return */ @requestmapping(value = "/download") public void downloadmedia(httpservletresponse response, httpservletrequest request) { inputstream inputstream = null; outputstream outputstream = null; try { //处理中文乱码 request.setcharacterencoding("utf-8"); string filename = request.getparameter("filename"); filename = new string(filename.getbytes("iso8859-1"),"utf-8"); //处理浏览器兼容 response.setcontenttype("application/msexcel;charset=utf-8");//定义输出类型 enumeration enumeration = request.getheaders("user-agent"); string browsername = (string) enumeration.nextelement(); boolean ismsie = browsername.contains("msie"); if (ismsie) { response.addheader("content-disposition", "attachment;filename=" + urlencoder.encode(filename, "utf8")); } else { response.addheader("content-disposition", "attachment;filename=" + new string(filename.getbytes("gb2312"), "iso8859-1")); } //url地址如果存在空格,会导致报错! 解决方法为:用+或者%20代替url参数中的空格。 filename = filename.replace(" ", "%20"); //图片下载 url url = new url(filename); urlconnection conn = url.openconnection(); outputstream = response.getoutputstream(); inputstream = conn.getinputstream(); ioutils.copy(inputstream, outputstream); } catch (ioexception e) { system.err.println(e); }finally { ioutils.closequietly(inputstream); ioutils.closequietly(outputstream); } }
以上就是本文的全部内容,希望对大家的学习有所帮助。