<p>package servlet;</p>
<p> </p>
<p>import java.io.File;</p>
<p>import java.io.FileInputStream;</p>
<p>import java.io.IOException;</p>
<p>import java.io.InputStream;</p>
<p>import java.net.URLEncoder;</p>
<p> </p>
<p>import javax.servlet.ServletException;</p>
<p>import javax.servlet.ServletOutputStream;</p>
<p>import javax.servlet.http.HttpServlet;</p>
<p>import javax.servlet.http.HttpServletRequest;</p>
<p>import javax.servlet.http.HttpServletResponse;</p>
<p> </p>
<p>public class DownLoadServlet extends HttpServlet {</p>
<p> </p>
<p>/**</p>
<p>doGet的方法</p>
<p> */</p>
<p> </p>
<p>public void doGet(HttpServletRequest request, HttpServletResponse response)</p>
<p>throws ServletException, IOException {</p>
<p> </p>
<p>// 获取下载图片的文件对象</p>
<p>String path=this.getServletContext().getRealPath("/<span style="font-family:宋体">中国</span><span style="font-family:Times New Roman">.jpg");</span></p>
<p>// 创建文件对象</p>
<p>File file=new File(path);</p>
<p>// 读取文件的流</p>
<p>InputStream is=new FileInputStream(file);</p>
<p>// 获取</p>
<p>String userAgent=request.getHeader("User-Agent");</p>
<p>if(userAgent.contains("Firefox")){</p>
<p>// 火狐浏览器的中文乱码解决</p>
<p>response.setHeader("Content-Disposition", "attachment; filename="+new String("<span style="font-family:宋体">中国</span><span style="font-family:Times New Roman">.jpg".getBytes("UTF-8"),"ISO8859-1" ));</span>
</p>
<p></p>
<p>}else{</p>
<p>//<span style="font-family:宋体">设置下载的头</span></p>
<p>// ie<span style="font-family:宋体">浏览器的中文字符解决</span></p>
<p>response.setHeader("Content-Disposition", "attachment; filename="+URLEncoder.encode("<span style="font-family:宋体">中国</span><span style="font-family:Times New Roman">.jpg", "UTF-8"));</span></p>
<p>}</p>
<p> </p>
<p> </p>
<p> </p>
<p>// 字节流</p>
<p>ServletOutputStream os=response.getOutputStream();</p>
<p>// 缓冲区</p>
<p>byte buffer[]=new byte[1024];</p>
<p>// 读取的长度</p>
<p>int len=0;</p>
<p>// 直到读取完毕</p>
<p>while((len=is.read(buffer))!=-1){</p>
<p>os.write(buffer,0,len);</p>
<p>}</p>
<p>// 关闭流</p>
<p>os.flush();</p>
<p>is.close();</p>
<p>os.close();</p>
<p>}</p>
<p> </p>
<p>/**</p>
<p>doPost的方法</p>
<p> */</p>
<p>public void doPost(HttpServletRequest request, HttpServletResponse response)</p>
<p>throws ServletException, IOException {</p>
<p>doGet(request, response);</p>
<p>}</p>
<p> </p>
<p>}</p>
<p> </p>
javaweb-图片的下载实现及分别处理浏览器乱码问题
最新推荐文章于 2022-12-15 20:04:26 发布