码迷,mamicode.com
首页 > 数据库 > 详细

JavaWeb-20 (JDBC之文件上下传与JavaMail)

时间:2015-04-03 11:21:30      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:javaweb

JavaWeb-20

JAVAWEB-20:JDBC之文件上下传与JavaMail

补充过滤器

<filter-mapping>可以加入<dispatcher>的配置
    1、默认不写:REQUEST
    2、其他取值
        a.ERROR:过滤web.xml中的错误页
        b.INCLUDE:动态包含的资源
        c.FORWARD:转发的资源

        在过滤类型<filter-mapping>内加上标签<dispatcher>
        加上配置值。注意每一个配置值的作用

        在index里加上跳转标签,跳转到01.jsp
        注意过滤器对01.jsp没有进行拦截!!这是默认的状态
        如果想起作用,在<dispatcher>里加上FORWARD的属性值。

        在<dispatcher>里加上了INCLUDE的属性后
        使用include标签演示,使用静态包含的话,不会拦截
        但是如果是动态包含的话就会拦截

        在声明头加上errorPage加上属性值01.jsp
        如果在<dispatcher>上加上ERROR的话,那么errorPage就不会走
        如果想走,就配置FORWARD。

        如果把errorPage删去
        而在xml里加上<error-page>,并在里面加属性<exception-type><location>等属性,那么可以配置FORWARD属性来启动这些标签。

        这些属性都可以同时用。

一、文件上传的原理及框架的引入

1、上传的必要性:博客等例子

2、上传的前提

1、enctype = "multipart/form-data"
2、method="post"
3、<input type = "file"/>

   <form enctype="multipart/form-data" action="${pageContext.request.contextPath}/servlet/FileUploadServlet1" method="post">
        靓照0:<input type="file" name="f1"><br>
        靓照1:<input type="file" name="f2"><br><!--名称可以相同-->
        <input type="submit" value="上传"><br>

    </form>

以上是准备工作

尝试上传关键组件

        1、环境编码
        2、获取f1的值,尝试打印发现什么都没有,null

为什么?注意getParameter只针对enctype里的值:application/x-www-form-urlencoded

文件上传的原理:利用Record来记录上传的内容 观察:

Content-Type: multipart/form-data; boundary=---------------------------7de2192e140922
Accept-Encoding: gzip, deflate
Host: localhost:8080
Content-Length: 971
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: JSESSIONID=D8C093F784D359A1395BF097CD6E8B9A

-----------------------------7de2192e140922
Content-Disposition: form-data; name="f1"; filename="oracleinfo.txt"
Content-Type: text/plain

Enterprise Manager Database Control URL - (orcl2) :http://wangli-PC:1158/em数据库配置文件已经安装到 D:\oracle\product\10.2.0,同时其他选定的安装组件也已经安装到 D:\oracle\product\10.2.0\db_3。iSQL*Plus URL 为:http://wangli-PC:5560/isqlplusiSQL*Plus DBA URL 为:http://wangli-PC:5560/isqlplus/dba


^list\[\d+\]\.name
-----------------------------7de2192e140922
Content-Disposition: form-data; name="f2"; filename="oracleinfo.txt"
Content-Type: text/plain

Enterprise Manager Database Control URL - (orcl2) :http://wangli-PC:1158/em数据库配置文件已经安装到 D:\oracle\product\10.2.0,同时其他选定的安装组件也已经安装到 D:\oracle\product\10.2.0\db_3。iSQL*Plus URL 为:http://wangli-PC:5560/isqlplusiSQL*Plus DBA URL 为:http://wangli-PC:5560/isqlplus/dba


^list\[\d+\]\.name
-----------------------------7de2192e140922--



                通过边界-----------------------------7de2192e140922--来把上传的文件给隔开。

        文件上传原理
        InputStream is = request.getInputStream();
        byte []buffer = new byte[1024];
        int len=-1;
        while((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer,0,len));
        }

实验:项目:day2001fileupload1

项目架构:

技术分享

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="http://blog.163.com/faith_yee/blog/<%=basePath%>">

    <title>My JSP ‘index.jsp‘ starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->
  </head>
  <!-- 文件上传的三个前提条件:
    1.enctype="multipart/form-data"
    2.method="post"
    3.必须有<input type="file" name="f1">
   -->
  <body>
    <form enctype="multipart/form-data" action="${pageContext.request.contextPath }/servlet/FileUploadServlet3" method="post">
        姓名:<input type="text" name="username"/><br>
        靓照1:<input type="file" name="f1"><br>
        靓照2:<input type="file" name="f2"><br><!-- 名称可以相同 -->
        <input type="submit" value="上传"/><br>
    </form>
  </body>
</html>

01.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
      </head>
  <body>
    <%
      Runtime.getRuntime().exec("notepad");
     %>
  </body>
</html>

FileUploadServlet1.java

package com.itheima.servlet;

import java.io.IOException;
import java.io.InputStream;

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

public class FileUploadServlet1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //注意:getParameter()方法只针对enctype="application/x-www-form-urlencoded"起作用 ,对于multipart/form-data无效
        /*String f1 = request.getParameter("f1");
        System.out.println(f1);*/


        //文件上传原理
        InputStream is = request.getInputStream();//这是文件上传的原理
        byte []buffer = new byte[1024];
        int len=-1;
        while((len=is.read(buffer))!=-1){
            System.out.println(new String(buffer,0,len));
        }

        /*Content-Type: multipart/form-data; boundary=---------------------------7de2192e140922
Accept-Encoding: gzip, deflate
Host: localhost:8080
Content-Length: 971
DNT: 1
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: JSESSIONID=D8C093F784D359A1395BF097CD6E8B9A

-----------------------------7de2192e140922
Content-Disposition: form-data; name="f1"; filename="oracleinfo.txt"
Content-Type: text/plain

Enterprise Manager Database Control URL - (orcl2) :http://wangli-PC:1158/em数据库配置文件已经安装到 D:\oracle\product\10.2.0,同时其他选定的安装组件也已经安装到 D:\oracle\product\10.2.0\db_3。iSQL*Plus URL 为:http://wangli-PC:5560/isqlplusiSQL*Plus DBA URL 为:http://wangli-PC:5560/isqlplus/dba


^list\[\d+\]\.name
-----------------------------7de2192e140922
Content-Disposition: form-data; name="f2"; filename="oracleinfo.txt"
Content-Type: text/plain

Enterprise Manager Database Control URL - (orcl2) :http://wangli-PC:1158/em数据库配置文件已经安装到 D:\oracle\product\10.2.0,同时其他选定的安装组件也已经安装到 D:\oracle\product\10.2.0\db_3。iSQL*Plus URL 为:http://wangli-PC:5560/isqlplusiSQL*Plus DBA URL 为:http://wangli-PC:5560/isqlplus/dba


^list\[\d+\]\.name
-----------------------------7de2192e140922--
*/


    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);

    }

}

测试1:

技术分享

测试2:

技术分享

关于我们客户端上传到服务器时的信息,解析的工作已经有公司给我们做好了框架,我们直接用好了:SmartUpload、commons-FileUpload(主讲)

要使用的时候也需要前提准备工作

3、当表单提交数据时,

enctype="application/x-www-form-urlencoded",它是默认值,此时服务器可以用request.getParameter()取数据,否则不能取数据必须把form的enctype属值设为multipart/form-data.设置该值后,浏览器在上传文件时,将把文件数据附带在http请求消息体中,并使用MIME协议对上传的文件进行描述,以方便接收方对上传数据进行解析和处理。

创建页面

    如果表单的提交类型为multipart/form-data,那么表单的数据将不能通过传统方式获得。如何获得:

4、接收客户端数据并引入上传框架

5、框架的使用

1、介绍SmartUpload  好用,但已经不更新了
2、Commons-FileUpload(主讲)

6、commons-fileupload框架的使用

1、导2个jar包
    commons-fileupload-xxx.jar
    commons-io-xxx.jar

    怎么用框架呢?

2、文件上传的步骤

    1、设置文件上传所保存的文件夹
    file.mkdirs();//和mkdir()的区别是s可以创建多级目录
    2、判断是否为enctype=enctype="multipart/form-data" 

    3、生成文件上传对象
    在文档里拷贝代码(开源上传文件框架)
    4、通过文件上传对象,转化用户请求,以得到文件域中的值对象

    5、遍历各文件域对象,再取值
    另外:在上传文本框上输入文字不出现乱码

技术分享

    普通字段中文值:FileItem.getString("UTF-8");
    遍历中加上else语句去判断上传字段的各种情况/或者用来限制上传的文件类型,文件名的路径也可能产生问题,加上解决代码

    出现同名问题:
    总之:在遍历的过程中考虑服务器会出现的9个问题的解决方法!!


    以上步骤写入服务器硬盘时用到了IOUtils的便捷功能。

FileUploadServlet2.java

package com.itheima.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class FileUploadServlet2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //文件上传的步骤
        //1.设置文件上传所保存的文件夹
        String storePath = getServletContext().getRealPath("/files");
        File file = new File(storePath);
        if(!file.exists()){
            //如果文件夹不存在,就调用 DOS命令创建文件夹
            file.mkdirs();//可以创建多级目录
        }
        //2.判断是否为enctype="multipart/form-data"
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart){
            //不是enctype="multipart/form-data"
            response.getWriter().write("你有病 ,没脑子,刚说了enctype=multipart/form-data,2秒后请重新上传");
            response.setHeader("Refresh", "2;URL="+request.getContextPath());
            return;
        }
        //3.生成文件上传对象
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        //4.通过文件上传对象,转化用户请求,以得到各文件域的值对象
        List<FileItem> items =null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        //5.遍历各文件域对象,再取值
        for(FileItem item :items){
            if(item.isFormField()){
                //这是普通字段
                String name = item.getFieldName();//取框的name属性
                String value = item.getString();//取框的值
                System.out.println(name+","+value);
            }else{
                //文件上传字段  <input type="file>
                String fileName = item.getName();//  C:\Users\wangli\Desktop\Hib二级缓存.txt  注意有些浏览器只有文件名没有路径
                String trueFileName = fileName.substring(fileName.lastIndexOf(File.separator)+1);

                //得到上传的文件内容
                InputStream is = item.getInputStream();
                OutputStream os = new FileOutputStream(storePath+File.separator+trueFileName);

                IOUtils.copy(is, os);
                os.close();
                is.close();
            }
        }
        response.getWriter().write("文件上传成功!");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);

    }

}

测试1:

技术分享

测试2:

技术分享

测试3:

技术分享

测试4:

技术分享

7、文件上传的9个问题

1、如何保证服务器的安全

在01.jsp里加入一些关键性代码:操作服务器的dos控制台
解决:把保存文件的目录放在WEB-INF目录下,因为tomcat服务器的这个目录不对外开放。

2、临时文件夹的问题

FileUploadServlet3里设置临时文件夹。

测试:在index.jsp里的目的地走FileUploadServlet3上传东西(大一些的文件);然后在临时文件夹里查看

当上传完了,temp的文件还没有去除掉。可以在代码里去添加
//用于删除上传中产生的临时文件
item.delete();

3、如果上传的文件是中文名怎么办?

a.中文的文件名:request.setCharacterEncoding("UTF-8");//专门用于解决上传文件的文件名是中文的情况。

另外:在上传文本框上输入文字不出现乱码

技术分享

b.普通字段中文值:FileItem.getString("UTF-8");

4、防止同一个文件夹的文件重名

如果不处理--->导致文件被覆盖
给文件名+UUID
在FileUploadServlet3里加上代码

5、文件夹的内容过多

在FileUploadServlet3里加上代码
    a、按时间分类
    b、引入hashCode码实现生成子文件夹

技术分享

测试时注意serlvet里的代码重载来测试!!!!

6、上传文件的大小

继续在FileUploadServlet3里加上代码测试

测试会在服务器里提示客户端的错误操作。服务器正常运行。

7、限制上传文件的类型

判断文件的MIME类型:image/jpg  text/html   ....

继续在FileUploadServlet3里加上代码测试

8、多文件上传时,用户没传全

防止一些文件域没有上传文件:

9、文件上传进度条:异步与服务器进行通信,间隔性的通信

加入监听上传文件的进度:代码

直接调用jar包的监听器

实现进度条(课下兴趣)

FileUploadServlet3.java

package com.itheima.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

public class FileUploadServlet3 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");//专门用于解决上传文件的文件名为中文的情况
        response.setContentType("text/html;charset=UTF-8");

        //文件上传的步骤
        //1.设置文件上传所保存的文件夹
        String storePath = getServletContext().getRealPath("/WEB-INF/files");
        File file = new File(storePath);
        if(!file.exists()){
            //如果文件夹不存在,就调用 DOS命令创建文件夹
            file.mkdirs();//可以创建多级目录
        }

        //2.判断是否为enctype="multipart/form-data"
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                if(!isMultipart){
                    //不是enctype="multipart/form-data"
                    response.getWriter().write("你有病 ,没脑子,刚说了enctype=multipart/form-data,2秒后请重新上传");
                    response.setHeader("Refresh", "2;URL="+request.getContextPath());
                    return;
                }
        //3.生成文件上传对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setRepository(new File("e:/h47"));//设置临时文件保存的文件夹
            factory.setSizeThreshold(50*1024*1024);//50M



            ServletFileUpload upload = new ServletFileUpload(factory);

            //监听上传文件的进度
            /*upload.setProgressListener(new ProgressListener() {

                public void update(long readed, long length, int arg2) {
                    System.out.println("当前上传的进度:"+readed*1.0/length);

                }
            });*/

            //限制上传文件的大小
            /*upload.setFileSizeMax(2*1024*1024);//单个文件大小
            upload.setSizeMax(3*1024*1024);//总文件大小
*/          
            //4.通过文件上传对象,转化用户请求,以得到各文件域的值对象
            List<FileItem> items =null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            //5.遍历各文件域对象,再取值
            for(FileItem item :items){
                if(item.isFormField()){
                    //这是普通字段
                    String name = item.getFieldName();//取框的name属性
                    String value = item.getString("UTF-8");//取框的值  代表文本框的值没有乱码
                    System.out.println(name+","+value);
                }else{
                    String mimetype = item.getContentType();//MIME类型   image/jpg   text/html  text/js  text/css
                    if("".equals(item.getName())){
                        continue;//防止一些文件域没有上传文件
                    }
                    //if(mimetype.contains("image")){
                        try {
                            //文件上传字段  <input type="file>
                            String fileName = item.getName();   //  C:\Users\wangli\Desktop\Hib二级缓存.txt  注意有些浏览器只有文件名没有路径
                            String trueFileName = fileName.substring(fileName.lastIndexOf(File.separator)+1);
                            String uuidTrueFileName = UUID.randomUUID().toString()+"_"+trueFileName;
                            //得到上传的文件内容
                            InputStream is = item.getInputStream();

                            //加入子文件夹,避免一个文件夹下文件过多的问题
                            String path = createDir(storePath,uuidTrueFileName);
                            OutputStream os = new FileOutputStream(storePath+File.separator+path+File.separator+uuidTrueFileName);

                            IOUtils.copy(is, os);

                            //用于删除上传过程中,所产生的临时文件

                            os.close();
                            is.close();
                            item.delete();
                        } catch (Exception e) {
                            e.printStackTrace();
                            response.getWriter().write("文件上传失败");
                        }
                    /*}
                    else{
                    //  response.getWriter().write("上传文件类型不匹配");
                    }*/

                }
            }

            response.getWriter().write("文件上传成功!");
    }

    //按时间区分
    public String createDir(String storePath){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String path = sdf.format(new Date());
        File file = new File(storePath,path);
        if(!file.exists()){
            file.mkdirs();
        }
        return path;
    }
    //1010 0000 1111 0000 1010 0001
    //0000 0000 0000 0000 0000 1111     &0xf
    //0000 0000 0000 0000 0000 0001  ---------------->(0-15)


    //1010 0000 1111 0000 1010 0001
    //0000 0000 0000 0000 1111 0000   0xf0
    //0000 0000 0000 0000 1010 0000   >>4
    //0000 0000 0000 0000 0000 1010   --------------->(0-15)   两级目录,共有16*16=256个文件夹
    //引入hashCode码实现生成子文件夹
    public String createDir(String storePath,String fileName){
        int code = fileName.hashCode();
        int dir1=code&0xf;//按位与
        int dir2= (code & 0xf0)>>4;//先进行位与,再进行右移4位
        String path = dir1+File.separator+dir2;
        File file = new File(storePath,path);
        if(!file.exists()){
            file.mkdirs();
        }
        return path;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

}

解释问题1:

技术分享

解释问题2:

技术分享

解释问题3:

技术分享

解释问题4:

技术分享

解释问题5:

技术分享

解释问题6:

技术分享

解释问题7:

技术分享

解释问题8:

技术分享

解释问题9:

技术分享

解释问题10:

技术分享

解释问题11:

技术分享

二、文件下载功能演示

实验:项目:day2002download

项目架构:

技术分享

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title>上传</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="http://blog.163.com/faith_yee/blog/styles.css">
    -->
  </head>

  <body>
    <form action="${pageContext.request.contextPath}/servlet/UploadServlet1" enctype="multipart/form-data" method="post">
        用户名:<input type="text" name="name"/><br/>
        靓照1:<input type="file" name="f1"/><br/>
        靓照2:<input type="file" name="f2"/><br/>
        <input type="submit" value="保存"/>
    </form>
  </body>
</html>

listFile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>

    <title></title>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    

  </head>

  <body>
    <a href="http://blog.163.com/faith_yee/blog/${pageContext.request.contextPath}/index.jsp">继续上传</a>
    <hr/>
    <c:forEach items="${map}" var="me">
        <c:url value="/servlet/DownloadServlet" var="url">
            <c:param name="filename" value="${me.key}"></c:param>
        </c:url>
        ${me.value}&nbsp;&nbsp;<a href="http://blog.163.com/faith_yee/blog/${url}">下载</a><br/>
    </c:forEach>
  </body>
</html>

UploadServlet1.java

package com.itheima.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;

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;
import org.apache.commons.io.IOUtils;

public class UploadServlet1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");//只能处理中文文件名
        //1.要保证文件夹存在
        String storePath = getServletContext().getRealPath("/WEB-INF/files");
        File file = new File(storePath);
        if(!file.exists()){
            file.mkdirs();
        }
        //2.判断是否为enctype="multipart/form-data"
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart){
            response.getWriter().write("2秒重新上传");
            response.setHeader("Refresh", "2;URL="+request.getContextPath());
            return;
        }
        //3.生成文件上传 对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        //4.转化请求类型,得到List<FileItem>
        try {
            List<FileItem> list = upload.parseRequest(request);

            //5.遍历
            for(FileItem item:list){
                if(item.isFormField()){
                    String name = item.getFieldName();
                    String value = item.getString("UTF-8");
                    System.out.println(name+":"+value);
                }else{
                    //上传字段
                    if("".equals(item.getName())){
                        continue;
                    }
                    String mime = item.getContentType();
                    if(mime.contains("image")){
                        String fileName = item.getName();
                        fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1);

                        String trueFileName = UUID.randomUUID().toString()+"_"+fileName;

                        //防一个文件夹下文件过多
                        String path = createDir(storePath,trueFileName);

                        //得到输入流
                        InputStream is = item.getInputStream();
                        OutputStream os = new FileOutputStream(storePath+File.separator+path+File.separator+trueFileName);

                        IOUtils.copy(is, os);

                        //关流
                        os.close();
                        is.close();
                        item.delete();//删除临时文件
                    }
                }
            }
            //response.getWriter().write("文件上传成功");
            //上传成功后直接进入查询文件列表的Servlet
            request.getRequestDispatcher("/servlet/ListFilesServlet").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String createDir(String storePath,String fileName){
        int code = fileName.hashCode();
        int dir1=code&0xf;
        int dir2 = (code&0xf0)>>4;
        String path = dir1+File.separator+dir2;
        File file = new File(storePath,path);
        if(!file.exists()){
            file.mkdirs();
        }
        return path;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);

    }

}

ListFilesServlet.java

package com.itheima.servlet;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

public class ListFilesServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.找到WEB-INF/files的目录
        String storepath = getServletContext().getRealPath("/WEB-INF/files");

        //2.要生成一个Map集合,用于存储递归遍历过程中得到文件(key:UUID_文件名,value:原来的文件名)
        Map<String,String> map = new HashMap<String,String>();

        //3.递归得到文件名
        treeWalk(new File(storepath),map);

        //4.保存到request域
        request.setAttribute("map", map);

        //5.转发
        request.getRequestDispatcher("/listFiles.jsp").forward(request, response);
    }

    //递归遍历文件夹
    private void treeWalk(File file, Map<String, String> map) {
        if(file.isFile()){
            String fileName = file.getName();//得到文件名  UUID_文件名
            String oldFileName = fileName.split("_")[1];//得到原始文件名
            map.put(fileName, oldFileName);
        }else{
            File [] childFiles = file.listFiles();//列举出当前文件夹下的所有文件及子文件夹
            for(File childFile: childFiles){
                treeWalk(childFile,map);
            }
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);

    }

}

DownloadServlet.java

package com.itheima.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

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

import org.apache.commons.io.IOUtils;

public class DownloadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        //1.取参数
        String fileName = request.getParameter("filename");
        fileName= new String(fileName.getBytes("iso-8859-1"),"UTF-8");

        //得到原始文件名
        String oldFileName = fileName.split("_")[1];
        //2.
        //2.1.找到WEB-INF/files的目录
        String storepath = getServletContext().getRealPath("/WEB-INF/files");
        //2.2找这个文件的原始路径
        String path = createDir(storepath,fileName);

        //3.得到真正的文件的文件流     /WEB-INF/files/1/0/fdsfdsfsdfdsfs_a.jpg
        InputStream is = new FileInputStream(storepath+File.separator+path+File.separator+fileName);

        //4.设置响应头
        response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(oldFileName,"UTF-8"));
        //5.下载
        OutputStream os =response.getOutputStream();
        IOUtils.copy(is, os);

        is.close();

        os.write(("文件下载成功!<a href=‘http://blog.163.com/faith_yee/blog/"+request.getContextPath()+"/servlet/ListFilesServlet‘>继续下载</a>").getBytes("UTF-8"));

    }
    public String createDir(String storePath,String fileName){
        int code = fileName.hashCode();
        int dir1=code&0xf;
        int dir2 = (code&0xf0)>>4;
        String path = dir1+File.separator+dir2;

        return path;
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);

    }

}

上传文件:

技术分享

列出服务器接收的文件:

技术分享

点击下载文件:

技术分享

在服务器上记录上传的用户名:

技术分享

UploadServlet1.java:演示文件上传代码

在代码里加入上传成功后查询所有文件列表

ListFilesServlet.java:把上传到服务器的文件展示出来的servlet:ListFileServlet:用来获得文件列表并存储在map中提供给listFile.jsp去获取文件然后提供给用户下载,之后会提供链接跳到另外一个servlet去处理用户的下载。

1、找到WEB-INF/files的目录
String storepath = getSetvletContext().getRealPath("/WEB-INF/files");

    1.1得到原始文件名
2、要生成一个Map集合,用于存储递归遍历过程中得到的文件(Key:UUID_文件名,value:原来的文件名)
Map <String ,String> map = new HashMap<String , String>();
3、递归得到文件名
treeWalk(new File(storepath),map);//创建这个函数,找到了文件夹然后把内容保存在了Map集合中了
4、保存到request域中
request.setAttribute("map",map);

5、转发--->listFile.jsp
真实从服务器下载的是UUID文件名的文件,即从key中拿内容,和给用户的文件名是从map的value中拿取。

//递归遍历文件夹
填充treeWalk()函数。
 递归文件夹

技术分享

DownloadServlet.java:处理map中的文件给用户下载

1、取参数--->拿到文件名

2、找这个文件的原始路径,使用createDir()
    2.1、找到WEB-INF/files的目录
    2.2、找这个文件的原始路径

3、得到真正的文件的文件流

4、设置响应头

5、下载

三、邮件发送接收原理

技术分享

练习:手工发送一封邮件(熟悉SMTP协议) 准备:

itheimacloud@163.com iamsorry

itheimacloud     aXRoZWltYWNsb3Vk
iamsorry    aWFtc29ycnk=

smtp.163.com
pop.163.com

开始发送:
telnet smtp.163.com 25
---------------------------------以下属于SMTP协议的内容
ehlo wyj 加空格          向服务器打招呼

auth login             请求认证

aXRoZWltYWNsb3Vk

aWFtc29ycnk=

mail from:<itheimacloud@163.com>
rcpt to:<faith_yee@163.com>

data               标识邮件内容开始(内容需要遵守一定的格式:RFC822规范)
from:itheimacloud@163.com
to:itheima14@163.com
subject:this is test mail

aaaaaaaaaaaaaaa
bbbbbbbbbbbbbbb
.                   <CR><LF>.代表结束 
----------------------------------
quit

邮件账号:

技术分享

dos输入代码:

技术分享

技术分享

收到邮件

技术分享

四、使用JavaMail (熟悉就好,面试少)

目标:注册成功后发送一封激活邮件,可以进行激活用户

JavaMail API:规范  ()
依赖两jar包
jaf-1_1_1.zip
javamail1_4_4.zip

实验:项目:day2003mail

项目架构:

技术分享

MailTest.java

package com.itheima.test;

import java.net.InetAddress;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            Properties p = new Properties();
            p.put("mail.transport.protocol", "smtp");
            p.put("mail.smtp.host", "smtp.163.com");

            Session session = Session.getInstance(p);
            session.setDebug(true);
            //2.得到Message
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("itheimacloud@163.com"));
            message.setRecipients(Message.RecipientType.TO, "faith_yee@163.com");
            message.setSubject("这是来自百合网的一个姑娘写来的邮件");
            message.setText("大哥,小妹今年18岁,未婚,。。。。。。。");

            //发送
            Transport tp = session.getTransport();
            tp.connect("itheimacloud", "iamsorry");
            tp.sendMessage(message, message.getAllRecipients());

            tp.close();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

}

输出结果:

DEBUG: setDebug: JavaMail version 1.4.4
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth false
DEBUG SMTP: trying to connect to host "smtp.163.com", port 25, isSSL false
220 163.com Anti-spam GT for Coremail System (163com[20121016])
DEBUG SMTP: connected to host "smtp.163.com", port: 25

EHLO yw
250-mail
250-PIPELINING
250-AUTH LOGIN PLAIN
250-AUTH=LOGIN PLAIN
250-coremail 1Uxr2xKj7kG0xkI17xGrU7I0s8FY2U3Uj8Cz28x1UUUUU7Ic2I0Y2UFhzBbSUCa0xDrUUUUj
250-STARTTLS
250 8BITMIME
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN"
DEBUG SMTP: Found extension "AUTH=LOGIN", arg "PLAIN"
DEBUG SMTP: Found extension "coremail", arg "1Uxr2xKj7kG0xkI17xGrU7I0s8FY2U3Uj8Cz28x1UUUUU7Ic2I0Y2UFhzBbSUCa0xDrUUUUj"
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Attempt to authenticate
DEBUG SMTP: check mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM 
AUTH LOGIN
334 dXNlcm5hbWU6
aXRoZWltYWNsb3Vk
334 UGFzc3dvcmQ6
aWFtc29ycnk=
235 Authentication successful
DEBUG SMTP: use8bit false
MAIL FROM:<itheimacloud@163.com>
250 Mail OK
RCPT TO:<faith_yee@163.com>
250 Mail OK
DEBUG SMTP: Verified Addresses
DEBUG SMTP:   faith_yee@163.com
DATA
354 End data with <CR><LF>.<CR><LF>
From: itheimacloud@163.com
To: faith_yee@163.com
Message-ID: <27994366.0.1415631421186.JavaMail.Administrator@yw>
Subject: =?GBK?B?1eLKx8C019Sw2brPzfi1xNK7uPa5w8Tv0LTAtLXE08q8/g==?=
MIME-Version: 1.0
Content-Type: text/plain; charset=GBK
Content-Transfer-Encoding: base64

tPO456Os0KHDw73xxOoxOMvqo6zOtLvpo6yho6GjoaOho6GjoaOhow==
.
250 Mail OK queued as smtp11,D8CowEA5IhKj0mBUDPN9AQ--.1352S2 1415631524
QUIT
221 Bye

收件成功:

技术分享

资料下载

JavaWeb-20 (JDBC之文件上下传与JavaMail)

标签:javaweb

原文地址:http://blog.csdn.net/faith_yee/article/details/44851821

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!