servlet實現(xiàn)圖片上傳功能
更新時間:2019年09月16日 08:45:30 作者:Nandeska
這篇文章主要為大家詳細介紹了servlet實現(xiàn)圖片的上傳,具有一定的參考價值,感興趣的小伙伴們可以參考一下
一個簡單的servlet例子,實現(xiàn)圖片的上傳功能,上傳的圖片給 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");//獲取參數(shù)值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(); } } }
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Mybatis動態(tài)SQL?foreach批量操作方法
這篇文章主要介紹了Mybatis動態(tài)SQL?foreach批量操作方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03Dubbo在Spring和Spring Boot中的使用詳解
這篇文章主要介紹了Dubbo在Spring和Spring Boot中的使用詳解,需要的朋友可以參考下2017-10-10使用SpringCache操作Redis緩存數(shù)據(jù)的示例代碼
SpringCache是一個框架,實現(xiàn)了基于注解的緩存功能,只需要簡單的加一個注解,就能實現(xiàn)緩存功能,本文給大家介紹了如何使用SpringCache操作Redis緩存數(shù)據(jù),文中有相關的代碼示例供大家參考,需要的朋友可以參考下2024-01-01SpringMVC處理器映射器HandlerMapping詳解
這篇文章主要介紹了SpringMVC處理器映射器HandlerMapping詳解,在SpringMVC中會有很多請求,每個請求都需要一個HandlerAdapter處理,具體接收到一個請求之后使用哪個HandlerAdapter進行處理呢,他們的過程是什么,需要的朋友可以參考下2023-09-09關于Spring的AnnotationAwareAspectJAutoProxyCreator類解析
這篇文章主要介紹了關于Spring的AnnotationAwareAspectJAutoProxyCreator類解析,Spring是一個開源免費的框架 , 容器,是一個輕量級的框架 ,需要的朋友可以參考下2023-05-05