`

上传下载文件的两个servlet

阅读更多

这是自己之前做文件上传的例子,写给自己看的:

upload:

 

  public void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     response.setCharacterEncoding("UTF-8");
  request.setCharacterEncoding("UTF-8");

  PrintWriter out = response.getWriter();
  
        try {
      String fileValidateClass = request.getParameter("fileValidateClass");
      String fileUploadPath = request.getParameter("fileUploadPath");

      if (fileUploadPath == null || fileUploadPath.equals("")) {
       ConfigurationService c = (ConfigurationService) Context.getBean("configurationService");
       String uploadPath = c.getConfigtationValue("configuration.file.upload.path");
       
       fileUploadPath = FileUtils.getRealPath(request, "/" + uploadPath);
      }

   File fileParent = new File(fileUploadPath);
   if (!fileParent.exists()) {
    fileParent.mkdirs();
   }
   
   DiskFileItemFactory dfif = new DiskFileItemFactory();
   dfif.setSizeThreshold(DEFAULT_SIZE_THRESHOLD);
   dfif.setRepository(new File(fileUploadPath));

   
   ServletFileUpload sfu = new ServletFileUpload(dfif);
   sfu.setSizeMax(DEFAULT_SIZE_MAX);
   List<FileItem> fileItems = sfu.parseRequest(request);
      
   
      if (fileValidateClass != null && !fileValidateClass.equals("")) {
    UploadValidation fileValidate = null;
    try {
     fileValidate = (UploadValidation) Class.forName(
       fileValidateClass).newInstance();
    } catch (ClassNotFoundException e) {
     throw new ClassNotFoundException("Can't find Class:" + fileValidateClass);
    }
    
    String validateinfo = fileValidate.validateFilename(fileItems, fileUploadPath);
    if (validateinfo == null || validateinfo.equals("")) {
     throw new Exception(validateinfo);
    }
   }
           
            String realFile = null;
   String shortName = null;
   String fileNameInSession = "";
   
            for (FileItem fileItem : fileItems) {
    shortName = fileItem.getName().substring(
      fileItem.getName().lastIndexOf("\\") + 1,
      fileItem.getName().length());
    fileNameInSession = request.getSession().getId() + System.currentTimeMillis();
    realFile = fileUploadPath + System.getProperty("file.separator") + fileNameInSession + "_" + shortName;
    fileItem.write(new java.io.File(realFile));
    
    request.getSession().setAttribute("fileNameInSession", fileNameInSession);
            }
           
            out.print("{success:true,realFile:'"+fileNameInSession+"'}");
        } catch (Exception e) {
            logger.error(e);
            out.print("{error:'"+e.getMessage()+"'}");
        }
        out.close();
    }

 

 

download:

 

public void doService(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  
  response.setCharacterEncoding("UTF-8");
  request.setCharacterEncoding("UTF-8");

  OutputStream o = response.getOutputStream();

  String fileName = request.getParameter("fileName");
  String romotefileInfo = request.getParameter("romotefileInfo");

  if (fileName != null) {
   try {
    String uploadPath = request.getParameter("uploadPath");
    String downloadPath = "";
    if (uploadPath == null || uploadPath.trim().equals("")) {
     ConfigurationService c = (ConfigurationService) Context.getBean("configurationService");
     uploadPath = c.getConfigtationValue("configuration.file.upload.path");
     downloadPath = FileUtils.getRealPath(request, "/" + uploadPath);
    } else {
     downloadPath = uploadPath;
    }
    
    //download file from hard driver
    String pathname = downloadPath + fileName;
    File fileLoad = new File(pathname);

    int index = fileName.indexOf("_");
    String name = fileName.substring(index + 1);

    response.setHeader("Content-disposition", "attachment;filename=" + "" + name + "");
    response.setContentType("text/plain");
    
    long fileLength = fileLoad.length();
    String length = String.valueOf(fileLength);
    response.setHeader("Content_Length", length);
    
    // download the file.
    FileInputStream in = new FileInputStream(fileLoad);
    int n = 0;
    byte b[] = new byte[1024];
    while ((n = in.read(b)) != -1) {
     o.write(b, 0, n);
    }
   } catch (Exception e) {
    logger.error(e);
    o.write(new String("errro to download file").getBytes());
   }
   o.close();
  } else if (romotefileInfo != null) {
   try {
    //download file from database
    String filedownRemoteClass = request
      .getParameter("filedownClass");
    DownLoadFromRemote downLoadFromRemote = (DownLoadFromRemote) Class
      .forName(filedownRemoteClass).newInstance();
    byte[] filecontents = downLoadFromRemote
      .getFileFromRemote(romotefileInfo);
    String[] filelist = romotefileInfo.split(";");
    String remotefileName = filelist[2];

    //get the short name
    int index = remotefileName.indexOf("_");
    String name = remotefileName.substring(index + 1);

    BufferedOutputStream stream = null;
    File file = new File(name);
    FileOutputStream fstream = new FileOutputStream(file);
    stream = new BufferedOutputStream(fstream);
    stream.write(filecontents);
    stream.flush();
    
    response.setHeader("Content-disposition", "attachment;filename=" + "" + name + "");
    response.setContentType("text/plain");
    
    // get the file length.
    long fileLength = file.length();
    String length = String.valueOf(fileLength);
    response.setHeader("Content_Length", length);
    
    // download the file.
    FileInputStream in = new FileInputStream(file);
    byte b[] = new byte[1024];
    int n = 0;
    while ((n = in.read(b)) != -1) {
     o.write(b, 0, n);
    }
   } catch (ClassNotFoundException e) {
    logger.error(e);
    o.write(new String("errro to download file: " + e.getMessage()).getBytes());
   } catch (InstantiationException e) {
    logger.error(e);
    o.write(new String("errro to download file: " + e.getMessage()).getBytes());
   } catch (IllegalAccessException e) {
    logger.error(e);
    o.write(new String("errro to download file: " + e.getMessage()).getBytes());
   } catch (Exception e) {
    logger.error(e);
    o.write(new String("errro to download file: " + e.getMessage()).getBytes());
   }
   
   o.close();
  }
 }

分享到:
评论

相关推荐

    用servlet写的文件上传及下载功能带进度条

    com.fm.FileManagerService:一个servlet用来实现主要的文件上传下载逻辑的 com.fm.MyPreogressListener:一个进度监听类,用来做上传进度条的 jquery-1.9.1.js index.jsp:文件列表页面 upload.jsp:文件上传form...

    servlet+jsp实现上传下载文件用到的两个JAR包

    commons-io-1.4.jar commons-fileupload-1.2.1.jar

    纯jsp,servlet版的多文件上传与下载

    纯jsp,servlet版的文件上传与下载.同时可以上传两个文件,也可以自己修改下代码上传多个文件,这是本人的自己的代码,不是为了赚点积分,还真有点舍不得上传。工程名写成了了nostruts,是为了区分struts,用jsp写的

    纯jsp+servlet版的多文件上传与下载

    使用mvc模式设计,jsp+servlet开发,同时可以上传两个文件,也可以自己修改下代码上传多个文件,在Servlet中使用开源fileupload包实现文件上传功能

    Java文件上传的Servlet

    两个文件上传到指定的文件里,如何处理输入输出流。借用了Apache的commons-fileupload-1.2.1.jar来完成文件上传。

    servlet 处理上传文件所需的两个包

    这两个包 在处理上传 文件的时候用的到 web 处理中

    Ajax + servlet 实现上传进度条显示

    利用Ajax和Servlet实现文件上传,用来commons-fileupload和commons-io两个包。这两个包也在里边。东西做的很简单,但重点是能对这个方法有所了解就行了,有人想做的更炫的可以自行修改。希望能对大家有所帮助。如果...

    用JSPServlet实现文件上传.rar

    【摘要】:该文介绍了在B/S模式下,通过JSP/Servlet技术实现文件上传的方法。...笔者主要介绍用JSP方式和Servlet方式实现的两个代码简短又高效率的文件上传功能。在此基础上,可以对文件上传功能进行进一步的完善......

    Servlet上传文件

    * 2) 利用 request 获取 真实路径 ,供临时文件存储,和 最终文件存储 ,这两个存储位置可不同,也可相同 * 3)对 DiskFileItemFactory 对象设置一些 属性 * 4)高水平的API文件上传处理 ServletFileUpload ...

    如何使用servlet和commons-fileupload-1.2.1.jar和commons-io-2.4.jar两个jar包实现文件上传的功能

    本文件为一个MyEclipse工具开发的java web 工程压缩文件。本工程用于演示如何使用servlet和commons-fileupload-1.2.1.jar和commons-io-2.4.jar两个jar包实现文件上传的功能。

    Servlet实现文件上传,可多文件上传示例

    一、Servlet实现文件上传,需要添加第三方提供的jar包 下载地址: 1) commons-fileupload-1.2.2-bin.zip: 点击打开链接 2) commons-io-2.3-bin.zip: 点击打开链接  接着把这两个jar包放到 lib文件夹下: 二:...

    Servlet文件上传

    1、通过界面上传文件(一个或两个文件) 2、上传文件存放在服务器上指定文件下 3、servlet处理上传文件过程 4、上传成功后跳转到结果页面

    文件上传下载用到的jar包

    用servlet技术实现文件上传下载我们需要导入两个额外的jar包,一个是common-io-2.2.jar,另一个是commons-fileupload-1.3.1.jar,将这个两个jar 包导入WEB-INF/lib目录里

    关于zhaobq 的Ajax+servlet上传进度条的改进

    感谢zhaobq给我们提供了Ajax+servlet实现上传进度条。但此代码运行时会有一点小问题:1、点上传时会...但此处还有一个问题:如果同时开两个IE进行上传时,则两个上传进度条会显示是一样的。希望哪位能解决这个问题。

    JSP文件的上传和下载

    使用Servlet进行文件的上传与下载,用到commons-fileupload-1.3.3.jar和commons-io-2.6.jar两个jar包。

    Flex+Java Servlet文件上传实例

    Eclipse工程文件包含两个jar 博文链接:https://yexin218.iteye.com/blog/207219

    servlet和jsp学习指南pdf

    第11章展示如何利用Servlet 3的文件上传特性,以及如何在客户端改善用户的体验;第12章解释如何通过编程方式将资源发送到浏览器;第13章介绍如何利用Decorator模式以及类来改变Servlet请求和响应的行为;第14章讨论...

    jsp+servlet实现文件上传与下载功能

    本文实例为大家分享了jsp servlet实现文件上传与下载的具体代码,供大家参考,具体内容如下 上传: 需要导入两个包:commons-fileupload-1.2.1.jar,commons-io-1.4.jar import java.io.File; import java.io....

    servlet和jsp学习指南

    第11章展示如何利用Servlet3的文件上传特性,以及如何在客户端改善用户的体验;第12章解释如何通过编程方式将资源发送到浏览器;第13章介绍如何利用Decorator模式以及类来改变Servlet请求和响应的行为;第14章讨论...

    文件的上传与下载

    这是一个文件上传与下载的源码,其中有Servlet和Struts2两种,代码可以直接运行。

Global site tag (gtag.js) - Google Analytics