servlet实现图片上传功能
更新时间:2019年09月16日 08:45:30 作者:Nandeska
这篇文章主要为大家详细介绍了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();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Eclipse+Java+Swing+Mysql实现电影购票系统(详细代码)
这篇文章主要介绍了Eclipse+Java+Swing+Mysql实现电影购票系统并附详细的代码详解,需要的小伙伴可以参考一下2022-01-01
maven springboot如何将jar包打包到指定目录
这篇文章主要介绍了maven springboot如何将jar包打包到指定目录,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-12-12
SpringBoot整合redis中的JSON序列化文件夹操作小结
在我们日常的项目开发中,使用redis作为缓存,来提高系统访问速度和缓解系统压力,在使用中遇到几个问题,本文给大家详细总结下,对SpringBoot整合redis JSON序列化相关知识感兴趣的朋友一起看看吧2022-02-02
浅谈java中类名.class, class.forName(), getClass()的区别
下面小编就为大家带来一篇浅谈java中类名.class, class.forName(), getClass()的区别。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-05-05
spring-boot整合Micrometer+Prometheus的详细过程
这篇文章主要介绍了springboot整合Micrometer+Prometheus的详细过程,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧2024-05-05


最新评论