⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fileservice.java

📁 自己用JSP做的文件上传和下载组件
💻 JAVA
字号:
package shen.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import shen.util.ChineseUtil;
import shen.util.LogUtil;

public class FileService implements IFileService
{
	// 存放表单中的数据(表单名称,表单值)
	private Map<String, String> formElements = new HashMap<String, String>();
	
	/* (non-Javadoc)
	 * @see shen.service.IFileService#upload(javax.servlet.http.HttpServletRequest, java.lang.String)
	 */
	public boolean upload(HttpServletRequest request, String uploadDirPath) throws IOException
	{
		// 获取客户端的请求输入流
		ServletInputStream is = request.getInputStream();
		// 进行文件上传
		return uploadFile(is, uploadDirPath);
	}
	
	/* (non-Javadoc)
	 * @see shen.service.IFileService#download(javax.servlet.http.HttpServletResponse, java.lang.String, java.lang.String)
	 */
	public boolean download(HttpServletResponse response, String serverDirPath, String fileName) throws IOException
	{
		// 设置下载头部信息
		response.setContentType("application/octet-stream");
	    response.setHeader("Content-Disposition","attachment;" + " filename="+
						 ChineseUtil.toUtf8String(fileName));
	    // 进行下载文件
	    return downloadFile(response.getOutputStream(), serverDirPath, fileName);
	}
	
	/* (non-Javadoc)
	 * @see shen.service.IFileService#getFileByDir(java.lang.String)
	 */
	public String[] getFileByDir(String fileDir)
	{
		File file = new File(fileDir);
		// 若文件目录不存在或文件不是目录,返回null
		if ((!file.exists()) || (!file.isDirectory()))
		{
			return null;
		}
		return file.list();
	}
	
	/**
	 * 具体的上传文件动作
	 * @param is 输入流
	 * @param clientPath 客户端的文件路径
	 * @param serverDirPath 服务器的目录路径
	 * @return 上传成功或失败
	 */
	private boolean uploadFile(ServletInputStream is, String serverDirPath)
	{
		try
		{
			// 缓冲区
			byte[] buff = new byte[4096];
			// 读取文件标记
			String sign = "";
			int len = is.readLine(buff, 0, buff.length);
			sign = new String(buff, 0, len);
			sign = sign.substring(sign.lastIndexOf("-") + 1, sign.length() - 2);
			// 从输入流中获取上传的文件名称
			String fileName = "";
			String line = "";
			while (true)
			{
				// 读取一行
				len = is.readLine(buff, 0, buff.length);
				if (len == -1)
				{
					break;
				}
				line = new String(buff, 0, len, "utf-8");
				// 判断读出的行中有没有"filename="
				int pos = line.indexOf("filename=");
				if (pos > 0)
				{
					fileName = line.substring(pos + 10, line.length() - 3);
					fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
					// 读取文件类型行
					is.readLine(buff, 0, buff.length);
					// 读取一个空行
					is.readLine(buff, 0, buff.length);
					break;
				}
				// 判断此行是否为表单名称行
				pos = line.indexOf("name=");
				if (pos > 0)
				{
					// 获取表单元素名称
					String elementName = line.substring(pos + 6, line.length() - 3);
					// 读取一个空行
					is.readLine(buff, 0, buff.length);
					// 读取表单元素的值
					len = is.readLine(buff, 0, buff.length);
					line = new String(buff, 0, len, "utf-8");
					String elementValue = line.substring(0, line.length() - 2);
					// 放入表单对象中
					this.formElements.put(elementName, elementValue);
				}
			}
			System.out.println("filename = " + fileName);
			// 创建要写入的文件流
			OutputStream out = new FileOutputStream(new File(serverDirPath, fileName));
		
			// 缓冲读取的一行字符串
			boolean hasSign = false;
			byte[] nextBuff = new byte[4096];
			int nextLen = 0;
			String temp = null;
			String next = null;
			len = is.readLine(buff, 0, buff.length);
			temp = new String(buff, 0, len);
			while (len > 0)
			{
				if (next != null)
				{
					// 把下一行付给当前行
					buff = java.util.Arrays.copyOf(nextBuff, nextLen);
					len = nextLen;
				}
				// 若当前行为标记行,则退出循环
				if (temp.indexOf(sign) >= 0)
				{
					break;
				}
				// 获取下一行数据
				nextLen = is.readLine(nextBuff, 0, nextBuff.length);
				next = new String(nextBuff, 0, nextLen);
				// 若下一行数据有标志位, 当前行的数据去掉回车和换行 
				if (next.indexOf(sign) >= 0)
				{
					hasSign = true;
					len = len - 2;
				}
				// 放入当前数据
				out.write(buff, 0, len);
				if (hasSign)
				{
					break;
				}
			}
			
			// 刷新输出流
			out.flush();
			// 关闭输入输出流
			out.close();
			//reader.close();
			is.close();
			
			return true;
		} 
		catch (FileNotFoundException e)
		{
			LogUtil.log("建立上传文件时失败!");
			e.printStackTrace();
		} 
		catch (IOException e)
		{
			LogUtil.log("上传文件失败!");
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	 * 下载文件
	 * @param os 输出流
	 * @param serverDirPath 服务器的目录路径
	 * @param fileName 要下载的文件名称
	 * @return 下载文件成功或失败
	 */
	private boolean downloadFile(OutputStream os, String serverDirPath,
			String fileName)
	{
		try
		{
			// 创建输入流
			InputStream is = new FileInputStream(new File(serverDirPath, fileName));
			// 定义数据缓冲区
			byte[] buff = new byte[1024];
			// 读取的字节数
			int readLen = 0;
			// 循环读取输入流中的数据写入输出流中
			while((readLen = is.read(buff, 0, buff.length)) != -1)
			{
				os.write(buff, 0, readLen);
			}
			// 刷新输出流
			os.flush();
			// 关闭输入输出流
			is.close();
			os.close();
			
			return true;
		} 
		catch (FileNotFoundException e)
		{
			LogUtil.log("找不到下载的文件!");
			e.printStackTrace();
		} 
		catch (IOException e)
		{
			LogUtil.log("下载文件时出错,请重新下载!");
			e.printStackTrace();
		}
		
		return false;
	}
	
	/**
	 * 获取表单元素的值
	 * @param name
	 * @return
	 */
	public String getParameter(String name)
	{
		if (this.formElements.containsKey(name))
		{
			return this.formElements.get(name);
		}
		
		return null;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -