• Demo: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();
    }
    }

    }

  • 相关阅读:
    appium之adb常用命令
    测试基础之等价类
    selenium之CSS定位
    括号序列的最小代价
    Spark相对于MapReduce的优势
    Cache系统设计
    [京东2017实习生笔试] 终结者C
    [京东2017实习生笔试] 通过考试
    [hihoCoder] 1078. 线段树的区间修改
    [转载] 一步一步理解线段树
  • 原文地址:https://www.cnblogs.com/ly570/p/11498555.html
Copyright © 2020-2023  润新知