zoukankan      html  css  js  c++  java
  • Servlet+Jsp实现图片或文件的上传功能

    首先,我们创建一个新的web工程,在工程的WebRoot目录下新建一个upload文件夹,这样当我们将该工程部署到服务器上时,服务器便也生成个upload文件夹,用来存放上传的资源。

            然后,在WebRoot目录下新建一个jsp文件,主要实现的作用就是选择上传的文件,提交至servlet来进行处理

           详细代码如下:一个form将文件信息通过post方式传送到指定的servlet

    <%@ page language="java" contentType="text/html; charset=GBK"
     pageEncoding="GBK"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    </head>
    <body>
      <form action="UpLoad" method="post" enctype="multipart/form-data"> 
         请选择上传的图片或文件:<input type="file" name="fileName"/><input type="submit" value="上传"/> 
        </form> 
    </body>
    </html>

    可以看到,我们将数据提交到工程下的upload/UpLoad。

     

                 之后,我们就来编写这个servlet——UpLoad.java

    package ayds;

    import java.io.File;
    import java.io.IOException;
    import java.util.List;

    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;

    public class UpLoad extends HttpServlet {

     /**
      *
      */
     private static final long serialVersionUID = 1L;
     public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
    doPost(request, response);
    }
     @SuppressWarnings("unchecked") 
        @Override 
       
    //    protected void service(HttpServletRequest req, HttpServletResponse resp) 
    //            throws ServletException, IOException { 
      public void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
            req.setCharacterEncoding("GBK"); 
            resp.setContentType("text/html;charset=GBK"); 
            //为解析类提供配置信息 
            DiskFileItemFactory factory = new DiskFileItemFactory(); 
            //创建解析类的实例 
            ServletFileUpload sfu = new ServletFileUpload(factory); 
            //开始解析 
            sfu.setSizeMax(1024*400); 
            //每个表单域中数据会封装到一个对应的FileItem对象上 
            try { 
                List<FileItem> items = sfu.parseRequest(req); 
                //区分表单域 
                for (int i = 0; i < items.size(); i++) { 
                    FileItem item = items.get(i); 
                    //isFormField为true,表示这不是文件上传表单域 
                    if(!item.isFormField()){ 
                        ServletContext sctx = getServletContext(); 
                        //获得存放文件的物理路径 
                        //upload下的某个文件夹   得到当前在线的用户  找到对应的文件夹 
                         
                        String path = sctx.getRealPath("/upload"); 
                        System.out.println("path=="+path); 
                        //获得文件名 
                        String fileName = item.getName(); 
                        System.out.println("fileName=="+fileName); 
                        //该方法在某些平台(操作系统),会返回路径+文件名 
    //                    fileName = fileName.substring(fileName.lastIndexOf("/")+1);
                        fileName = fileName.substring(fileName.lastIndexOf("\")+1);
                        System.out.println("fileName=="+fileName);
                        File file = new File(path+"\"+fileName); 
                        if(!file.exists()){ 
                            item.write(file); 
                            //将上传图片的名字记录到数据库中 
                         int j=Dao.insertImg(fileName, "无");
                              if(j==1){
                            resp.sendRedirect("index2.jsp");
                              }
                        } 
                    } 
                } 
            } catch (Exception e) { 
                e.printStackTrace(); 
            } 
             
        } 

    }

  • 相关阅读:
    Kruskal重构树学习笔记
    亚洲和欧洲的分界线是谁划分的?
    代码目录 (App_Code 目录)及namespace的理解
    Events解惑——来自MSDN
    HttpContext.Current.Response和Response有什么区别?
    Ramdisk 内存盘的使用
    MVC模式 介绍
    关于Windows Workflow Foundation 调试时的经验小解(不断添加)
    关于类成员变量的声明和实例化的时机
    软件名称备份
  • 原文地址:https://www.cnblogs.com/manmanlu/p/3458775.html
Copyright © 2011-2022 走看看