servlet实现图片上传功能
一个简单的servlet例子,实现图片的上传功能,上传的图片给 HttpServletResponse对象
publicclassBackGroundLogoServletextendsHttpServlet { privatestaticfinalLoggerm_logger=Logger.getLogger(BackGroundLogoServlet.class); @Override publicvoidinit(ServletConfigconfig)throwsServletException{ super.init(config); m_logger.debug("BackGroundLogoServletinit."); } @Override protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse) throwsServletException{ response.setContentType("image/png"); response.setHeader("Access-Control-Allow-Origin","*"); StringfileName=request.getParameter("filename");//获取参数值titlebar_logo.png Filefile=newFile("D:\\"+fileName);//读取D:\\titlebar_logo.png图片 FileInputStreamfis=null; BufferedOutputStreamout=null; try { fis=newFileInputStream(file); out=newBufferedOutputStream(response.getOutputStream()); byte[]buffer=newbyte[1024]; intlen; while((len=fis.read(buffer))!=-1) { //readthefilefromlocaldisk //writetoclient out.write(buffer,0,len); out.flush(); m_logger.debug("backgroundpicuploadsuccess!"); } } catch(FileNotFoundExceptione) { try { response.reset(); //setcontenttypeonceagain response.setContentType("text/html;charset=utf-8"); //giveerrormessagetoclient response.getWriter().println("文件未找到"); } catch(IOExceptione1) { e1.printStackTrace(); } e.printStackTrace(); } catch(IOExceptione) { e.printStackTrace(); } finally { try { if(fis!=null){ fis.close(); } if(out!=null){ out.close(); } } catch(IOExceptione) { e.printStackTrace(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。