java上傳附件,批量下載附件(一)


上傳附件代碼:借助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("不是文件,那就不下載了,因為前台會做處理,此處就不在一步步進行驗證了!");
   }
  }
 }

}

 


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM