欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

servlet实现文件上传、预览、下载、删除功能

程序员文章站 2024-02-26 11:32:40
servlet实现文件上传,预览,下载和删除,供大家参考,具体内容如下 一、准备工作:   1.1 文件上传插件:uploadify;   1.2 文件上传所需jar...

servlet实现文件上传,预览,下载和删除,供大家参考,具体内容如下

一、准备工作:

  1.1 文件上传插件:uploadify;

  1.2 文件上传所需jar包:commons-fileupload-1.3.1.jar和commons-io-2.2.jar

  1.3 将数据转成json对象需要jar包:commons-beanutils-1.8.3.jar、commons-collections-3.2.1.jar、commons-lang-2.6.jar、commons-logging-1.1.3.jar、ezmorph-1.0.6.jar和json-lib-2.4-jdk15.jar

servlet实现文件上传、预览、下载、删除功能

  1.4 开发工具:我用的是eclipse,随意

  1.5 目录结构

servlet实现文件上传、预览、下载、删除功能

需要注意的是:变更uploadify.css文件中的取消文件上传图片的路径

.uploadify-queue-item .cancel a {
  background: url('../images/uploadify-cancel.png') 0 0 no-repeat;
  float: right;
  height:  16px;
  text-indent: -9999px;
  width: 16px;
} 

二、代码展示

2.1 客户端代码设计

jsp部分

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
  <head> 
    <title>演示-操作文件</title>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <script type="text/javascript" src="<c:url value="/js/jquery-1.11.2.min.js"/>"></script>
    <script type="text/javascript" src="<c:url value="/uploadify/js/jquery.uploadify-3.2.1.min.js"/>"></script>
    <link href="<c:url value=" rel="external nofollow" /uploadify/css/uploadify.css"/>" type="text/css" rel="stylesheet"/>
    <script type="text/javascript">var baseurl = '<%=request.getcontextpath()%>';</script>
    <script type="text/javascript" src="<c:url value="/index.js"/>"></script>
    <style type="text/css">
      /* 上传、取消上传按钮style start */
      .button {
        width: 80px;
        margin: 3px 1px 0 5px;
        padding: 0 10px;
        background-color: #16a0d3;
        border: none;
        display: inline-block;
        font-family: "microsoft yahei";
        font-size: 14px;
        cursor: pointer;
        height: 30px;
        line-height: 30px;
        color: #fff;
        border-radius: 5px;
        text-decoration:none;
        text-align:center;
      }
      
      .buttonover {
        width: 80px;
        margin: 3px 1px 0 5px;
        padding: 0 10px;
        background-color: #117ea6;
        border: none;
        display: inline-block;
        font-family: "microsoft yahei";
        font-size: 14px;
        cursor: pointer;
        height: 30px;
        line-height: 30px;
        color: #fff;
        border-radius: 5px;
        text-decoration:none;
        text-align:center;
      }  
      /* end 上传、取消上传按钮style */
    </style>
  </head>
  <body>
    <!-- 文件上传 -->
    <div id="file_upload"></div>
    <div id="ctrlupload" style="display:none;">
      <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('#file_upload').uploadify('upload', '*');" class="button" 
        onmouseover="javascript:this.classname='buttonover'" onmouseout="javascript:this.classname='button'">
            上传所有
      </a>  
      <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="$('#file_upload').uploadify('cancel', '*');$('#ctrlupload').hide();" class="button"
        onmouseover="javascript:this.classname='buttonover'" onmouseout="javascript:this.classname='button'">
            取消上传
      </a>  
    </div>
    <table border=1 style="border-collapse: collapse;" id="tablefiles">
      <thead>
        <th>序号</th>
        <th>文件名</th>
        <th>文件预览</th>
        <th>文件下载</th>
        <th>文件删除</th>
      </thead>
      <tbody></tbody>
    </table>
  </body>
</html>

js文件

var operatefile = new operatefile();
window.onload = function() {
  operatefile.init();
  
}

/**
 * 对文件进行操作
 * @returns
 */
function operatefile() {
  var object = this;
  
  /**
   * 初始化操作:
   */
  this.init = function() {
    // 队列中的文件数
    var selectedcount = 0;
    $('#file_upload').uploadify({
      'method' : 'get',// 默认值post,设置成get是为了向后台传递自定义的参数
      'auto' : false,// 设置为true当选择文件后就直接上传了,为false需要点击上传按钮才上传。默认值为true
      'buttontext' : '添加文件',// 按钮文本
      'filetypeexts' : '*.gif; *.jpg; *.png;*.pdf;*.zip;',// 限制上传文件类型,默认值没有限制(*.*)
      'filetypedesc' : '请选择gif jpg png pdf zip类型的文件',// 这个属性值必须设置filetypeexts属性后才有效,用来设置选择文件对话框中的提示文本,默认值:all files
      'swf' : baseurl + '/uploadify/flash/uploadify.swf', // flash文件路径(帮助我们与后端交互数据)
      'uploader' : baseurl + '/uploadfile.do' , // 处理文件上传请求地址 
      'formdata' : {'param1':'测试文件上传'},// 请求参数:上传每个文件的同时提交到服务器的额外数据
      'ondialogclose' : function(queuedata) {
        // 获取该队列中有多少个要上传的文件 
        var queuesize = $('#file_upload-queue').children('div').length;
        if (queuesize > 0) {
          $('#ctrlupload').show();
        }
      },
      'onuploadsuccess' : function(file, data, response) {// 上传成功
        // 将josn字符串转换成json对象
        data = eval('(' + data + ')');
        // 获取页面上文件展示table 有多少行
        var rowslength = $('#tablefiles')[0].rows.length;
        // 设置查看文件所需参数
        var param = "filename=" + data.filename;
        // 查看文件请求地址
        var viewurl = baseurl + '/viewfile.do?' + param;
        // 下载文件请求地址
        var downloadurl = baseurl + '/downloadfile.do?' + param;
        
        // 拼接一行tr
        var trtemplate = '<tr>'
                +  '<td>'
                +    rowslength   
                +  '</td>'
                +  '<td>'
                +    file.name // 仍展示原文件名
                +  '</td>'
                +  '<td>'
                +    '<a href="' + viewurl + '" rel="external nofollow" target="_blank">点击预览</a>'
                +    '<input type="hidden" name="imgaddress" value="' + data.filename + '"/>'
                +  '</td>'
                +  '<td>'
                +    '<a href="' + downloadurl + '" rel="external nofollow" >点击下载</a>'
                +  '</td>'
                +  '<td>'
                +    '<a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="operatefile.deletefile(\'' + data.filename + '\',' + rowslength +');">点击删除</a>'
                +  '</td>'
                +'</tr>';
        $('#tablefiles').append(trtemplate);
      },
      'onuploaderror' : function(file, errorcode, errormsg, errorstring) {// 上传失败
        
      }
    });
    
  }
  
  /**
   * 删除文件
   * @param 文件名
   */
  this.deletefile = function(filename,rowindex) {
    // 设置删除文件所需参数
    var param = "filename=" + filename;
    // 删除文件请求地址
    var deleteurl = baseurl + '/deletefile.do?' + param;
    $.get(
      deleteurl, 
      function(msg) {
        alert(msg);
        if ("删除失败!" != msg) {
          // 删除该行记录
          $('#tablefiles')[0].deleterow(rowindex);
        }
      }
    );
    
  }
  
} 

2.2 服务器端代码设计

文件上传代码(fileupload.javae文件)

package controller.filehandler;

import java.io.file;
import java.io.ioexception;
import java.io.printwriter;
import java.util.hashmap;
import java.util.iterator;
import java.util.list;
import java.util.map;
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.fileuploadexception;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
import net.sf.json.jsonobject;

public class fileupload extends httpservlet {
  private static final long serialversionuid = 1l;

  protected void doget(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    this.dopost(request, response);
  }

  /**
   * 处理文件上传的post
   * @precaution 下方的类名出自包import org.apache.commons.fileupload.*
   */
  protected void dopost(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    // 1.设置参数编码
    request.setcharacterencoding("utf-8");
    // 设置响应数据字符集
    response.setcharacterencoding("utf-8");
    // 设置响应数据格式
    // response.setcontenttype("application/json; charset=utf-8");
    printwriter out = response.getwriter();
    // 2.创建文件上传处理工厂
    diskfileitemfactory factory = new diskfileitemfactory();
    // 3.设置临时文件存放地点
    // 3.1获取当前web应用程序对象(web容器在启动时,它会为每个web应用程序都创建一个对应的servletcontext对象,它代表当前web应用)
    servletcontext servletcontext = this.getservletconfig().getservletcontext();
    // 3.2获取服务器的临时目录(tomcat、weblogic)
    // d:\programfiles(x86)\apache\tomcat\apache-tomcat-7.0.40-x86\work\catalina\localhost\demo
    file repository = (file) servletcontext.getattribute("javax.servlet.context.tempdir");
    // 3.3临时文件将会存储在该目录下
    factory.setrepository(repository);
    // 4.创建文件上传处理器
    servletfileupload upload = new servletfileupload(factory);
    // 5.判断请求类型是否为文件上传类型
    boolean multipartcontent = upload.ismultipartcontent(request);

    map<string, string> mapdata = new hashmap<string, string>();
    // 返回信息
    string msg = "";
    // 错误信息
    string errormsg = "";
    // 文件名
    string filename = "";
    if (multipartcontent) {
      try {
        // 获取请求参数
        string param = request.getparameter("param1");
        system.out.println(param);
        // 6.解析请求信息
        list<fileitem> items = upload.parserequest(request);

        // 7.对所有请求信息进行判断
        iterator<fileitem> iter = items.iterator();
        while (iter.hasnext()) {
          fileitem item = iter.next();
          // 信息为文件格式
          if (!item.isformfield()) {
            filename = processuploadedfile(param, item);
            msg = "上传成功!";
          }
        }
      } catch (fileuploadexception e) {
        e.printstacktrace();
        msg = "上传失败!";
        errormsg = e.getmessage();
      }

    } else {
      msg = "form表单类型不是multipart/form-data,无法上传!";
    }

    mapdata.put("msg", msg);
    mapdata.put("errormsg", errormsg);
    mapdata.put("filename", filename);
    // 将map转成json
    jsonobject jsondata = jsonobject.fromobject(mapdata);
    // 返回客户端信息
    out.print(jsondata.tostring());
  }

  /**
   * 处理上传的文件
   * @param org_id
   * @param order
   * @param item
   */
  @suppresswarnings("unused")
  private string processuploadedfile(string param, fileitem item) {
    // process a file upload
    string fieldname = item.getfieldname();// 默认值为filedata
    // 获取文件名
    string filename = item.getname();
    // 内容类型:application/octet-stream
    string contenttype = item.getcontenttype();
    boolean isinmemory = item.isinmemory();
    // 获取文件大小
    long sizeinbytes = item.getsize();
    // 1.指定文件上传的根路径
    string path = this.getservletcontext().getrealpath("/web-inf/uploadfiles");
    // 2.路径构成:/uploadfile/filename
    // todo 可以自定义文件存放路径
    // 3.根据路径批量创建文件夹
    file filedirectories = new file(path);
    // 目录不存在时,再创建
    if (!filedirectories.exists()) {
      filedirectories.mkdirs();// 所有的文件夹都创建成功才返回true
    }
    // 4.文件名格式校验(文件名中不能包含#号)
    int index = filename.indexof("#");
    if (index > -1) {
      filename = filename.replace('#', '_');
    }
    // todo 可以对文件名进行重命名
    // 5.在指定路径下创建指定名称的文件
    file uploadedfile = new file(path + "/" + filename);
    // 6.判断该文件是否已存在
    if (!uploadedfile.exists()) {
      try {
        // 使用了这个方法写入文件,临时文件会被系统自动删除
        item.write(uploadedfile);
      } catch (exception e) {
        e.printstacktrace();
      }
    }
    // 返回重名后的文件名
    return filename;
  }

  /**
   * 处理信息为普通的格式
   * @param item
   */
  private void processformfield(fileitem item) {
    // process a regular form field
    if (item.isformfield()) {
      string name = item.getfieldname();
      string value = item.getstring();
    }
  }
}

文件查看代码(fileview.java文件)

package controller.filehandler;

import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import javax.servlet.servletcontext;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

public class fileview extends httpservlet {
  private static final long serialversionuid = 1l;

  // 设定输出的类型
  private static final string gif = "image/gif;charset=utf-8";
  private static final string jpg = "image/jpeg;charset=utf-8";
  private static final string png = "image/png;charset=utf-8";
  private static final string pdf = "application/pdf;charset=utf-8";
  private static final string zip = "application/zip;charset=utf-8";

  protected void doget(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    this.dopost(request, response);
  }

  /**
   * 处理文件查看的post
   * @throws ioexception
   * @precaution 下方的类名出自包import org.apache.commons.fileupload.*
   */
  protected void dopost(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    // 文件流
    inputstream is = null;
    // 输入缓冲流
    bufferedinputstream bis = null;
    // 得到输出流
    outputstream output = null;
    // 输出缓冲流
    bufferedoutputstream bos = null;
    // 1.设置参数编码
    request.setcharacterencoding("utf-8");
    // 2.设置响应数据字符集
    response.setcharacterencoding("utf-8");
    // 3.获取客户端请求参数:文件名
    string filename = request.getparameter("filename");
    // 4.重置response
    response.reset();
    // 5.设置响应数据格式
    if (filename.endswith(".gif")) {
      response.setcontenttype(gif);
    } else if (filename.endswith(".jpg")) {
      response.setcontenttype(jpg);
    } else if (filename.endswith(".png")) {
      response.setcontenttype(png);
    } else if (filename.endswith(".pdf")) {
      response.setcontenttype(pdf);
    } else if (filename.endswith(".gif")) {
      response.setcontenttype(gif);
    } else if (filename.endswith(".zip")) {
      response.setcontenttype(zip);
    }

    string filepath = "web-inf/uploadfiles/" + filename;
    // 获取当前web应用程序
    servletcontext webapp = this.getservletcontext();
    // 6.获取指定文件上传的真实路径
    filepath = webapp.getrealpath(filepath);
    // 7.读取目标文件,通过response将目标文件写到客户端
    is = new fileinputstream(filepath);
    bis = new bufferedinputstream(is);
    output = response.getoutputstream();
    bos = new bufferedoutputstream(output);
    byte data[] = new byte[1024];// 缓冲字节数
    int size = bis.read(data);
    while (size != -1) {
      bos.write(data, 0, size);
      size = bis.read(data);
    }

    // 关闭流
    bis.close();
    bos.flush();// 清空输出缓冲流
    bos.close();
    output.close();
  }

}

文件下载代码(filedownload.java文件)

package controller.filehandler;

import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

public class filedownload extends httpservlet {
  private static final long serialversionuid = 1l;

  protected void doget(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    this.dopost(request, response);
  }

  /**
   * 处理文件下载的post
   * @throws ioexception
   */
  protected void dopost(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    // 1.设置参数编码
    request.setcharacterencoding("utf-8");
    // 设置响应数据字符集
    response.setcharacterencoding("utf-8");
    // 1.获得请求文件名
    string filename = request.getparameter("filename");
    // 2.设置文件mime类型(指定要返回内容的类型)
    response.setcontenttype(getservletcontext().getmimetype(filename));
    // 3.设置content-disposition(指定下载该文件时的文件名)
    response.setheader("content-disposition", "attachment;filename=" + filename);
    // 4.读取目标文件,通过response将目标文件写到客户端
    // 4.1 获取目标文件的绝对路径
    string filepath = "web-inf/uploadfiles/" + filename;
    filepath = this.getservletcontext().getrealpath(filepath);
    // 4.2 读取文件
    inputstream in = new fileinputstream(filepath);
    // 4.3 输出文件
    outputstream out = response.getoutputstream();
    // 写文件
    int n;
    while ((n = in.read()) != -1) {
      out.write(n);
    }

    in.close();
    out.close();
  }

}

文件删除代码(filedelete.java文件)

package controller.filehandler;

import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

public class filedelete extends httpservlet {
  private static final long serialversionuid = 1l;

  protected void doget(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    this.dopost(request, response);
  }

  /**
   * 处理文件下载的post
   * @throws ioexception
   */
  protected void dopost(httpservletrequest request, httpservletresponse response)
      throws servletexception, ioexception {
    // 1.设置参数编码
    request.setcharacterencoding("utf-8");
    // 设置响应数据字符集
    response.setcharacterencoding("utf-8");
    // 2.获得请求文件名
    string filename = request.getparameter("filename");
    // 3.获取该文件所在路径
    string filepath = "web-inf/uploadfiles/" + filename;
    filepath = this.getservletcontext().getrealpath(filepath);
    // 4.在指定路径下创建指定名称的文件
    file deletefile = new file(filepath);
    boolean flag = false;
    string msg = "";
    // 5.判断该文件是否已存在
    if (deletefile.exists()) {
      flag = deletefile.delete();
      if (flag) {
        msg = "删除成功!";
      } else {
        msg = "删除失败!";
      }
    } else {
      msg = "该文件不存在!";
    }

    // 6.返回客户端操作信息
    response.getwriter().print(msg);
  }

}

web.xml代码

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="webapp_id" version="2.5">
 <display-name>demo_uploadanddownload</display-name>
  <context-param>
    <param-name>webapprootkey</param-name>
    <param-value>uploadanddownload</param-value>
  </context-param>
  <!-- 处理文件的servlet -->
  <!-- 文件上传 start -->
  <servlet>
    <servlet-name>upload</servlet-name>
    <!-- 配置处理文件上传的java类 -->
    <servlet-class>controller.filehandler.fileupload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>upload</servlet-name>
    <!-- 设置文件上传请求路径 -->
    <url-pattern>/uploadfile.do</url-pattern>
  </servlet-mapping>
  <!-- end 文件上传 -->
  <!-- 文件预览 start -->
  <servlet>
    <servlet-name>view</servlet-name>
    <!-- 配置处理文件预览的java类 -->
    <servlet-class>controller.filehandler.fileview</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>view</servlet-name>
    <!-- 设置文件预览请求路径 -->
    <url-pattern>/viewfile.do</url-pattern>
  </servlet-mapping>
  <!-- end 文件预览 -->
  <!-- 文件下载 start -->
  <servlet>
    <servlet-name>download</servlet-name>
    <!-- 配置处理文件下载的java类 -->
    <servlet-class>controller.filehandler.filedownload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>download</servlet-name>
    <!-- 设置文件下载请求路径 -->
    <url-pattern>/downloadfile.do</url-pattern>
  </servlet-mapping>
  <!-- end 文件下载 -->
  <!-- 文件删除 start -->
  <servlet>
    <servlet-name>delete</servlet-name>
    <!-- 配置处理文件删除的java类 -->
    <servlet-class>controller.filehandler.filedelete</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>delete</servlet-name>
    <!-- 设置文件删除请求路径 -->
    <url-pattern>/deletefile</url-pattern>
  </servlet-mapping>
  <!-- end 文件删除 -->
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

2.3 代码优化

处理文件查看(fileview.java) ,设置响应文件类型,可以用下面这句话替换

response.setcontenttype(getservletcontext().getmimetype(filename) + ";charset=utf-8");

三、效果展示

servlet实现文件上传、预览、下载、删除功能

servlet实现文件上传、预览、下载、删除功能

servlet实现文件上传、预览、下载、删除功能

servlet实现文件上传、预览、下载、删除功能

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。