使用DWR框架完成文件上传与下载

本文主要介绍使用ajax框架——DWR完成文件的上传与下载

一、  创建Maven模块

    这里不详述过程


二、  编辑pom.xml

    下面罗列我所需要用到的依赖


        
        <dependency>
            <groupId>javaxgroupId>
            <artifactId>javaee-web-apiartifactId>
            <version>7.0version>
            <scope>providedscope>
        dependency>
        
        <dependency>
            <groupId>org.directwebremotinggroupId>
            <artifactId>dwrartifactId>
            <version>3.0.1-RELEASEversion>
        dependency>
        
        <dependency>
            <groupId>commons-logginggroupId>
            <artifactId>commons-loggingartifactId>
            <version>1.2version>
        dependency>
        
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.1version>
        dependency>
        
        <dependency>
            <groupId>org.apache.tikagroupId>
            <artifactId>tika-coreartifactId>
            <version>1.12version>
        dependency>
        
        <dependency>
            <groupId>commons-langgroupId>
            <artifactId>commons-langartifactId>
            <version>2.6version>
        dependency>

    另外我使用了jetty作为Web容器

  <plugin>
      <groupId>org.eclipse.jettygroupId>
      <artifactId>jetty-maven-pluginartifactId>
      <version>9.2.10.v20150310version>
      <configuration>
      <webAppConfig>
          <contextPath>/dwrcontextPath>
      webAppConfig>
      <httpConnector>
          <port>8787port>
      httpConnector>
      <scanIntervalSeconds>10scanIntervalSeconds>
      <stopKey>terminatestopKey>
      <stopPort>7878stopPort>
      configuration>
  plugin>

三、  编辑web.xml

    注册DWR的监听器【这里DWR的监听器并非必须】和Servlet。

    
    <listener>
        <listener-class>org.directwebremoting.servlet.DwrListenerlistener-class>
    listener>

    
    <servlet>
        <servlet-name>dwr-invokerservlet-name>
        <servlet-class>org.directwebremoting.servlet.DwrServletservlet-class>
         
        <init-param>
            <param-name>fileUploadMaxBytesparam-name>
            <param-value>104857600param-value>
        init-param>
         
        <init-param>
            <param-name>debugparam-name>
            <param-value>trueparam-value>
        init-param>
        
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>dwr-invokerservlet-name>
        <url-pattern>/dwr/*url-pattern>
    servlet-mapping>

    顺带一提:我使用的DWR是3.0.1-REALEASE版本,另外用的比较多的还有3.0.M1里程碑版本。这两个版本对监听器的注册有所不同, 3.0.M1版本没有DwrListener这个类, 需要由另外两个监听器来实现,这里不展开,有需要的话可以Google、百度。【不知道是不是不同Maven镜像下载下来的依赖略有不同,因为我有朋友使用3.0.M1版本就有DwrListener这个类】


四、  编写文件上传与下载的服务类

    文件上传UploadService.java

/**
 * @Date : 2016-03-15 9:57
 * @Author : junbin chung
 * @Email : [email protected]
 * @Intro : 提供文件批量上传服务
 */
public class UploadService {

    /**
     * 功能:根据文件传输器批量上传文件到webapp/upload目录下
     *
     * @param fileTransfers 从页面传递过来的DWR的文件传输器数组
     * @throws IOException
     */
    public void batchUpload(FileTransfer[] fileTransfers) throws IOException {
        // 通过webContext可以获得Servlet API的大多数常用对象
        WebContext webContext = WebContextFactory.get();
        String realPath = webContext.getServletContext().getRealPath("/upload");

        for (FileTransfer fileTransfer : fileTransfers) {
            String name = FilenameUtils.getName(fileTransfer.getFilename());
            // 如果没有选择文件,则文件名为空,故不应该为它作上传处理
            if (StringUtils.isEmpty(name)) {
                continue;
            }
            InputStream inputStream = fileTransfer.getInputStream();
            FileUtils.copyInputStreamToFile(inputStream, new File(realPath, name));
        }
    }

    这里说明一下,文件上传接收的参数除了FileTransfer类型之外,还有一个比较常用的类型是InputStream。但是由于FileTransfer可以获得更多的信息,所以一般采用FileTransfer类型。


    文件下载Download.java

/**
 * @Date : 2016-03-15 9:59
 * @Author : junbin chung
 * @Email : [email protected]
 * @Intro : 提供文件下载服务
 */
public class DownloadService {

    /**
     * 功能:获取webapp/upload目录下的文件名称列表
     *
     * @return 文件名称列表
     */
    public String[] listFiles() {
        WebContext webContext = WebContextFactory.get();
        String realPath = webContext.getServletContext().getRealPath("/upload");
        File dir = new File(realPath);
        return dir.list();
    }

    /**
     * 功能:根据指定名称获取文件并提供下载
     *
     * @param filename 文件名称
     * @return DWR文件传输器
     * @throws IOException
     */
    public FileTransfer downloadFile(String filename) throws IOException {
        WebContext webContext = WebContextFactory.get();
        String realPath = webContext.getServletContext().getRealPath("/upload");
        File file = new File(realPath, filename);
        if (file.exists() && file.isFile()) {
            // 使用Tika检测文件的MIME
            Tika tika = new Tika(TikaConfig.getDefaultConfig());
            return new FileTransfer(new String(filename.getBytes("UTF-8"), "ISO-8859-1"), // 转化字符编码,避免中文乱码
                    tika.detect(file), file.length(), new FileInputStream(file));
        }
        throw new FileNotFoundException("文件名称:" + filename
                + "\n对不起,资源已被删除或者不再提供该资源的下载服务!");
    }

}

五、  在dwr.xml中公布Service类

    其一、我们需要在webapp/WEB-INF/目录下创建一个dwr.xml文件并引入DWR的dtd
    其二、公布UploadService和DownloadService。



<dwr>

    <allow>
        
        <create creator="new">
            <param name="class" value="org.junbin.dwr_in_action.service.UploadService"/>
            <include method="batchUpload"/>
        create>
        <create creator="new">
            <param name="class" value="org.junbin.dwr_in_action.service.DownloadService"/>
            <include method="listFiles"/>
            <include method="downloadFile"/>
        create>
    allow>

dwr>

    要点说明:

  1. create标签的creator属性有多种属性值,比较常用的是new,还有spring【与Spring集成的时候就选择这个】。
  2. param标签常用name属性设置为class,value指定为要公布的完全限定类名。
  3. include标签指定该类中要公布的方法名称,exclude标签指定该类中不公布的方法名称。
  4. 当选择new的时候,需要确保该类有一个无参构造方法【隐式或者显式】;通常建议使用include标签。

六、  编辑文件上传下载的jsp文件

    6.1、文件上传upload.jsp
        6.1.1、引入js文件

<head>
    <title>文件上传title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-1.8.3.js">script>
    
    <script type="text/javascript" src="${pageContext.request.contextPath}/dwr/engine.js">script>
    
    <script type="text/javascript" src="<%=request.getContextPath()%>/dwr/interface/UploadService.js">script>
head>

        6.1.2、文件上传div

<div id="batch">
    <label>请选择文件:<input type="file" name="batch"/>label><br/>

    <button id="append" type="button">继续添加button>
    <button id="upload" type="button">上传button>
div>

        6.1.3、DWR处理批量上传


                    
                    

你可能感兴趣的:(DWR)