SmartUpload組件實現文件上傳,文件下載,打包下載。


jsp頁面部分

 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- jsp 頁面部分 -->
<!-- 文件上傳時必須要設置表單的enctype="multipart/form-data"
	讓表單中的數據以二進制的方式提交,在servlet中以字節流獲取

-->
<!--  
<h1>使用jsp+servlet進行文件上傳和下載</h1>
 <form action="/fileUpload/UploadFile" method="post" enctype="multipart/form-data">
  		請選擇圖片:<input id="myfile" name="myfile" type="file" />
  		<input type="submit" value="提交"  />${result}
</form>
下載:<a href="/fileUpload/DownloadServlet?filename=01.txt">01.txt</a>
-->

<!--  
<hr>
<h1>使用SmartUpload組件實現文件上傳和下載</h1>
 <form action="/fileUpload/SmartFileUpload" method="post" enctype="multipart/form-data">
  		請選擇圖片:<input  name="myfile" type="file" />
  		<input type="submit" value="提交"  />${result}
</form>
下載:<a href="/fileUpload/SmartFileDownload?filename=01.txt">01.txt</a>

-->



<hr>
<h1>使用SmartUpload組件批量下載文件,通過打包下載方式</h1>
<form action="/fileUpload/SmartFileDownloadMore" method="post">
圖片一:<input name="file" type="checkbox" value="01.jpg" />    
圖片二:<input name="file" type="checkbox" value="02.jpg" />    
圖片三:<input name="file" type="checkbox" value="03.jpg" />    
圖片四:<input name="file" type="checkbox" value="04.jpg" />    
<input type="submit" value="上傳" />${more}
</form>
</body>
</html>


 

文件上傳:

package com.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

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

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req,resp);
	}

	/**
	 * jsp+servlet文件上傳
	 * 思路:通過request.getInputStream()獲取表單的流信息,然后FileOutputStream寫到臨時文件,然后截取所需要的字節
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/**
		 * 第一步:
		 * 通過request.getInputStream()獲取表單的流信息
		 * 然后通過FileOutputStream()保存到臨時文件中
		 */
		//從request當中獲取流信息
		InputStream fileSource = req.getInputStream();
		String tempFileName = "E:/tempFile";
		//tempFile指向臨時文件
		File tempFile = new File(tempFileName);
		//outputStram文件輸出流指向這個臨時文件
		FileOutputStream outputStream = new FileOutputStream(tempFile);
		byte b[] = new byte[1024];
		int n;
		while(( n = fileSource.read(b)) != -1){
			outputStream.write(b, 0, n);
		}
		//關閉輸出流、輸入流
		outputStream.close();
		fileSource.close();
		
		/**
		 * 第二步:
		 * 通過RanomAccessFile 流讀取第二行,來截取文件名
		 */
		
		//獲取上傳文件的名稱
		RandomAccessFile randomFile = new RandomAccessFile(tempFile,"r");
		randomFile.readLine();
		String str = randomFile.readLine();
		System.out.println(str);
		int beginIndex = str.lastIndexOf("\\") + 1;
		int endIndex = str.lastIndexOf("\"");
		String filename = str.substring(beginIndex, endIndex);
		System.out.println("filename:" + filename);
		
		//重新定位文件指針到文件頭
		randomFile.seek(0);
		long startPosition = 0;
		int i = 1;
		//獲取文件內容 開始位置
		while(( n = randomFile.readByte()) != -1 && i <=4){
			if(n == '\n'){
				startPosition = randomFile.getFilePointer();
				i ++;
			}
		}
		startPosition = randomFile.getFilePointer() -1;
		//獲取文件內容 結束位置
		randomFile.seek(randomFile.length());
		long endPosition = randomFile.getFilePointer();
		int j = 1;
		while(endPosition >=0 && j<=2){
			endPosition--;
			randomFile.seek(endPosition);
			if(randomFile.readByte() == '\n'){
				j++;
			}
		}
		endPosition = endPosition -1;
		//設置保存上傳文件的路徑
		String realPath = "E:/圖片";
		System.out.println(realPath);
		File fileupload = new File(realPath);
		if(!fileupload.exists()){
			fileupload.mkdir();
		}
		File saveFile = new File(realPath,filename);
		RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile,"rw");
		//從臨時文件當中讀取文件內容(根據起止位置獲取)
		randomFile.seek(startPosition);
		while(startPosition < endPosition){
			randomAccessFile.write(randomFile.readByte());
			startPosition = randomFile.getFilePointer();
		}
		//關閉輸入輸出流、刪除臨時文件
		randomAccessFile.close();
		randomFile.close();
		tempFile.delete();
		
		req.setAttribute("result", "上傳成功!");
		RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/FileUpload.jsp");
		dispatcher.forward(req, resp);
	}
}

文件下載:

package com.fileupload;

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

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

/**
 * Servlet implementation class DownloadServlet
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	
	/**
	 * jsp+servlet文件下載
	 * 思路:用FileInputStream讀取下載的文件到內存,然后響應輸出流讓瀏覽器以附件的形式下載
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//需要下載的文件de路徑
		String path = "E:/圖片/";
		String filename = req.getParameter("filename");
		File file = new File(path + filename);
		if(file.exists()){
			resp.setContentType("application/x-msdownload");//設置相應類型application/octet-stream表示以附件的形式下載
			resp.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");//設置頭信息
			InputStream inputStream = new FileInputStream(file);
			//以流的形式獲取響應內容
			ServletOutputStream ouputStream = resp.getOutputStream();
			byte b[] = new byte[1024];
			int n ;
			while((n = inputStream.read(b)) != -1){
				ouputStream.write(b,0,n);
			}
			//關閉流、釋放資源
			ouputStream.close();
			inputStream.close();
			
			
		}else{
			req.setAttribute("errorResult", "文件不存在下載失敗!");
			RequestDispatcher dispatcher = req.getRequestDispatcher("jsp/FileUpload.jsp");
			dispatcher.forward(req, resp);
		}
		
		
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req,resp);
	}

	

}

文件批量導包下載:

package com.fileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

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

/**
 * Servlet implementation class SmartFileDownloadMore
 */
public class SmartFileDownloadMore extends HttpServlet {
	private static final long serialVersionUID = 1L;
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * SmartUpload文件批量下載
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//獲取下載的文件
		String url="E:/圖片";
		String[] name=request.getParameterValues("file");//獲取復選框中的值
		 
		//設置響應的方式和頭信息
		response.setContentType("application/x-msdownload");
		response.setHeader("Content-Disposition", "attachment;filename=test.zip");//設置zip附件的名字
		
		//將響應之后的輸出流包裝成zip輸出流來輸出
		ZipOutputStream zop=new ZipOutputStream(response.getOutputStream());
		for(String fileName:name){
			zop.putNextEntry(new ZipEntry(fileName));//為壓縮包中的每一項命名
			//用文件字節輸入流讀取文件后,以zip輸出流輸出
			File file =new File(url+"/"+fileName);
			//創建文件字節輸入流,將需要下載的文件讀到內存
			FileInputStream fis=new FileInputStream(file);
			byte b[]=new byte[1024];
			int len=-1;
			while((len=fis.read(b))!=-1){
				zop.write(b, 0, len);
			}
			fis.close();
		}
		zop.close();
//		request.setAttribute("more", "批量下載成功");
//		request.getRequestDispatcher("jsp/FileUpload.jsp").forward(request, response);
		
	}

}


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com