Demo:servlet实现图片的上传

Posted ly570

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
}
}

}

以上是关于Demo:servlet实现图片的上传的主要内容,如果未能解决你的问题,请参考以下文章

使用Servlet上传多张图片——Servlet层(ProductServlet.java)

Java Servlet图片上传至指定文件夹并显示图片

ckeditor 实现 servlet 图片上传 配置

Servlet实现单个图片,多个图片上传和图片的显示功能

Cookie中图片的浏览记录与cookie读取servle时路径的设置(文字描述)

JSP 实用程序之简易文件上传组件