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);
		
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值