servlet实现图片上传功能

时间:2021-05-19

一个简单的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(); } } }

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章