JSP上传显示图片代码

 Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在指定的文件夹中,也可以将图片存放在数据库,并支持四种常用的图片格式:jpg,png,gif,bmp。
  首先,跟上传一般文件一样,需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:
FileUploadServlet.java
java 代码
  1. package com.ek.servlet;   
  2. import java.awt.image.BufferedImage;   
  3. import java.io.ByteArrayOutputStream;   
  4. import java.io.File;   
  5. import java.io.IOException;   
  6. import java.io.InputStream;   
  7. import java.util.Iterator;   
  8. import java.util.List;   
  9. import java.util.regex.Matcher;   
  10. import java.util.regex.Pattern;   
  11. import javax.servlet.ServletException;   
  12. import javax.servlet.http.HttpServlet;   
  13. import javax.servlet.http.HttpServletRequest;   
  14. import javax.servlet.http.HttpServletResponse;   
  15. import org.apache.commons.fileupload.FileItem;   
  16. import org.apache.commons.fileupload.FileUploadException;   
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;   
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;   
  19. import com.ek.image.ImageUtil;   
  20. public class FileUploadServlet extends HttpServlet {   
  21.  /**  
  22.   *   
  23.   */  
  24.  private static final long serialVersionUID = 1L;   
  25.  private static String filePath = "";   
  26.  /**  
  27.   * Destruction of the servlet. 
     
  28.   */  
  29.  public void destroy() {   
  30.   super.destroy(); // Just puts "destroy" string in log   
  31.   // Put your code here   
  32.  }   
  33.  /**  
  34.   * The doPost method of the servlet. 
     
  35.   *   
  36.   * This method is called when a form has its tag value method equals to  
  37.   * post.  
  38.   *   
  39.   * @param request  
  40.   *            the request send by the client to the server  
  41.   * @param response  
  42.   *            the response send by the server to the client  
  43.   * @throws ServletException  
  44.   *             if an error occurred  
  45.   * @throws IOException  
  46.   *             if an error occurred  
  47.   */  
  48.  public void doPost(HttpServletRequest req, HttpServletResponse res)   
  49.    throws ServletException, IOException {   
  50.   res.setContentType("text/html; charset=UTF-8");   
  51.   DiskFileItemFactory factory = new DiskFileItemFactory();   
  52.   // maxi
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值