上传附件代码:借助commons-fileupload-1.2.jar

package com.str;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Iterator;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {
 
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
   doGet(req, resp);
 }
 
 
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  
  HttpServletRequest request = (HttpServletRequest)req; 
  HttpServletResponse response = (HttpServletResponse)resp; 
  
 /* response.setContentType("text/html;charset=gb2312");
  response.setCharacterEncoding("utf-8");*/
  
  OutputStream outputStream = null;   
  InputStream inputStream = null;
  
  DiskFileItemFactory factory = new DiskFileItemFactory(); 
  ServletFileUpload fileUpload = new ServletFileUpload(factory);
 
  try {
   List items = fileUpload.parseRequest(request); 
   for (Iterator iterator = items.iterator(); iterator.hasNext();) {   
    FileItem name = (FileItem) iterator.next();               
    if(!name.isFormField()){                     
     String fieldName  = name.getFieldName();  //这个是name值
     String fileName = name.getName();     //这个是全路径
     String lastFileName ="";
     
     //这句话获取的是源文件的原名称,不做任何修改
     String oldNamePath = fileName.substring(fileName.lastIndexOf("\\")+1);
     
     if(fileName.endsWith(".docx")|| fileName.endsWith(".xls")){
      
      lastFileName = request.getRealPath("/")+"\\upload\\"+ oldNamePath;
      outputStream = new FileOutputStream(new File(lastFileName )); 
      
      inputStream = name.getInputStream();                  
      byte[] bs = new byte[1024];                     
      int length = 0;                     
      while(null != inputStream && (length = inputStream.read(bs))!=-1){            
       outputStream.write(bs);    
      }  
     }
     outputStream.flush();
     }                            
    //把lastFileName存到数据库(这里就不写了不只lz用的什么方式)} 
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

}
}

单个下载文件,批量下载文件代码:借助于ant.jar包的ZipOutputStream、ZipEntry

package com.str;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

public class LoadServlet  extends HttpServlet {
 
 @Override
 /*protected void doGet(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException {
  
  String path = getServletContext().getRealPath("/") + "\\upload";
  OutputStream o = resp.getOutputStream();
  byte b[] = new byte[1024];
  
  //这个地方的文件,可以从数据库中动态查找,我这边写死了为了简单展示
  File fileLoad = new File(path, "解析类型配置.xls");
  
  String filename = new String("解析类型配置.xls".getBytes("gbk"), "iso8859-1");

System.out.println(filename);
  
  我记得在Excel导出数据的时候说过filename千万别写中文,其实经过以下:
  String filename = new String("解析类型配置.xls".getBytes("gbk"), "iso8859-1"); 
  转换以后,文件无论是中文、英文,都不会出现乱码情况,本人已验证
  
  resp.setHeader("Content-disposition", "attachment;filename="+ filename);
  
  long fileLength = fileLoad.length();    
  String length = String.valueOf(fileLength);   
  resp.setHeader("Content_Length", length);  
  FileInputStream in = new FileInputStream(fileLoad);      
  int n = 0;      
  while ((n = in.read(b)) != -1) {   
   o.write(b, 0, n);
   }
 }*/

//以上是单个下载附件,这边是批量压缩下载附件
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
 throws ServletException, IOException {
  
  String zipFileName = "test.zip";
  
  //这些文件都是存在的,我是写死了的,可以从页面传名称过来
  String[] filePathArray = {"1.jpg","2.jpg","3.xls","测试.docx"};   
  String path = getServletContext().getRealPath("/") + "\\image";
  
  resp.setContentType("application/x-msdownload" ); // 通知客户文件的MIME类型:
  resp.setHeader("Content-disposition","attachment;filename=" + zipFileName);
  
  ZipOutputStream zos = new ZipOutputStream(resp.getOutputStream());
  
  for (String filePath : filePathArray) {
   File file = new File(path + File.separator + filePath);
   doZip(file, zos);
  }   
  zos.close();
 }
 
 //处理批量下载时候,文件压缩问题
 private void doZip(File file, ZipOutputStream zos) throws IOException {
  if(file.exists()) {
   if (file.isFile()) {
    //如果是文件,写入到 zip 流中
    String fileName = file.getName();
    
    ZipEntry zet = new ZipEntry(file.getName());
    zos.putNextEntry(zet);
    FileInputStream fis = new FileInputStream(file);
    byte[] buffer = new byte[1024];
    int r = 0;
    while ((r = fis.read(buffer)) != -1) {
     zos.write(buffer, 0, r);
    }
    zos.setEncoding("gbk");   //这个地方很重要
    zos.flush();    
    fis.close();
   }else {
    System.out.println("不是文件,那就不下载了,因为前台会做处理,此处就不在一步步进行验证了!");
   }
  }
 }

}

java上传附件,批量下载附件(一)的更多相关文章

  1. java上传文件,下载文件

    1.上传文件 1 protected int doTask(BaseForm form) throws AppException, FatalException, NoExistsException, ...

  2. java+上传大文件

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 先说下要求: PC端全平台支持,要求支持Windows,Mac,Linux 支持所 ...

  3. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

  4. Jmeter和LR上传文件和下载

    Jmeter和LR上传文件和下载 背景: 在某个申请业务中,需要上传附件文件,然后才能提交该申请 遇到的问题: 1,  在使用Jmeter或者LR进行录制时,无法录制到上传文件的请求,只能通过Fidd ...

  5. java上传excel文件及解析

      java上传excel文件及解析 CreateTime--2018年3月5日16:25:14 Author:Marydon 一.准备工作 1.1 文件上传插件:swfupload: 1.2 文件上 ...

  6. Selenium(十一):设置元素等待、上传文件、下载文件

    1. 设置元素等待 前面我们接触了几个元素等待方法,sleep.implicitly_wait方法,这一章我们就来整体学一下. 现在大多数Web应用程序使用的都是AJAX技术.当浏览器加载页面时,页面 ...

  7. edtftpj让Java上传FTP文件支持断点续传

    在用Java实现FTP上传文件功能时,特别是上传大文件的时候,可以需要这样的功能:程序在上传的过程中意外终止了,文件传了一大半,想从断掉了地方继续传:或者想做类似迅雷下载类似的功能,文件太大,今天传一 ...

  8. java 上传文件到 ftp 服务器

    1.  java 上传文件到 ftp 服务器 package com.taotao.common.utils; import java.io.File; import java.io.FileInpu ...

  9. Struts2实现文件的上传与动态下载功能。

    本篇主要使用Struts2实现文件的上传与动态下载功能.出于安全考虑,所以,在硬盘上存储上传的文件的时候,统一都重新命名为随机字符串.用数据库存储真实文件名与随机文件名称之间的关联. 下面的是实体类 ...

  10. .net core版 文件上传/ 支持批量上传,拖拽以及预览,bootstrap fileinput上传文件

    asp.net mvc请移步 mvc文件上传支持批量上传,拖拽以及预览,文件内容校验 本篇内容主要解决.net core中文件上传的问题  开发环境:ubuntu+vscode 1.导入所需要的包:n ...

随机推荐

  1. Codeforces Round #564 (Div. 2) A. Nauuo and Votes

    链接:https://codeforces.com/contest/1173/problem/A 题意: Nauuo is a girl who loves writing comments. One ...

  2. Hive进阶_Hive的子查询

    - 集合中如果含null数据,不可使用not in, 可以使用in- hive只支持where和from子句中的子查询- 主查询和自查询可以不是同一张表 select e.ename from emp ...

  3. python 1 学习廖雪峰博客

    输出 用print()在括号中加上字符串,就可以向屏幕上输出指定的文字.比如输出'hello, world',用代码实现如下: >>> print('hello, world') p ...

  4. C. An impassioned circulation of affection DP

    http://codeforces.com/contest/814/problem/C 12ooyomioomioo21 o2 o 这题我是用dp解的,不过好像很慢,比赛的时候算了下不会mle,就没滚 ...

  5. [PHP] – 性能优化 – Fcgi进程及PHP解析优化

    https://www.abcdocker.com/abcdocker/808------[PHP] – 性能优化 – Fcgi进程及PHP解析优化

  6. PHP开发环境及搭建

    自学PHP中,很多东西都不熟悉,在此做个记录,方便以后再次搭建PHP环境.这篇文章基本按照原文  ThinkPHP5开发环境安装和配置 ,在此感谢该作者 一.实验目的 1.掌握ThinkPHP5(简称 ...

  7. ruby 正则表达式 匹配中文

    1.puts /[一-龥]+/.match("this is 中文")                 =>中文 2.str2="123中文"puts / ...

  8. echarts使用中的那些事儿( 三)

    饼图上的那些字与下面说明性的文字有些重合,该怎么缩小圆形的大小呢,还有它的位置,怎么让它向上一些或者向下一些: 有以下两个属性可以解决问题: radius : '55%', ------------这 ...

  9. 从wireshark数据中分析rtmp协议,并提取出H264视频流

    我写的小工具 rtmp_parse.exe 使用用法如先介绍下: -sps  [文件路径] 解析 sps 数据 文件当中的内容就是纯方本的hexstring: 如 42 E0 33 8D 68 05 ...

  10. Hybrid框架安全隐患分析

    Hybrid框架安全隐患分析 目前我司移动端项目中各种app如雨后春笋般生根发芽层出不穷.而利用Hybrid框架确实可以减轻一部分移动端压力.并且做到灵活发版.但是其中的安全问题往往让人忽略. 针对A ...