栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

servlet实现图片上传功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

servlet实现图片上传功能

一个简单的servlet例子,实现图片的上传功能,上传的图片给  HttpServletResponse 对象

public class BackGroundLogoServlet extends HttpServlet
{
   private static final Logger m_logger=Logger.getLogger (BackGroundLogoServlet. class);
   
   @Override
   public void init(ServletConfig config) throws ServletException {
      super.init(config);
      m_logger.debug ( "BackGroundLogoServlet init.");
   }
   
   @Override
   protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException{  
      response.setContentType( "image/png");
      response.setHeader( "Access-Control-Allow-Origin", "*");
      String fileName = request.getParameter( "filename");//获取参数值titlebar_logo.png
      File file = new File( "D:\"+ fileName);//读取D:\titlebar_logo.png图片
      FileInputStream fis = null;
      BufferedOutputStream out= null;
      try
      {
 fis = new FileInputStream(file);
 out = new BufferedOutputStream(response.getOutputStream());
 byte[] buffer= new byte[1024];
 int len;
 while((len=fis.read(buffer))!=-1)
 {
   //read the file from local disk
   //write to client
   out.write(buffer, 0, len);   
   out.flush();
   m_logger.debug ( "background pic upload success !");
 }
      }
      catch (FileNotFoundException e)
      {
 try
 {
   response.reset();
   //set content type once again
   response.setContentType("text/html;charset=utf-8" );
   //give error message to client
   response.getWriter().println( "文件未找到" );
 }
 catch (IOException e1)
 {
   e1.printStackTrace();
 }
 e.printStackTrace();
      }
      catch (IOException e)
      {
 e.printStackTrace();
      }
      finally
      {
 try
 {
   if(fis!= null){
   fis.close();
 }
 if(out!= null){
   out.close();
 }
      }
      catch (IOException e)
      {
 e.printStackTrace();
      }
    }
      
   }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/137028.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号