当前位置: 代码迷 >> Web前端 >> servlet 资料上传、下载
  详细解决方案

servlet 资料上传、下载

热度:163   发布时间:2012-07-01 13:15:00.0
servlet 文件上传、下载
<%@ 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>
<script src="common/js/jquery.js" type="text/javascript"></script>
<script src="common/js/ajaxfileupload.js" type="text/javascript"></script>
<script>
/** 利用ajax方式上传文件 **/
function uploadFile(){
	$.ajaxFileUpload({
		url : 'TestServlet?action=upload',
		secureuri : false,
		fileElementId : 'fileC',
		dataType: 'text',
		success : function(data,status){
			if(data.indexOf("上传文件失败!")==-1){
				var oldFileName = data.split("|")[0];
				var newFileName = data.split("|")[1];
				var fileListValue = $("#uploadFileList").html();
				var obj = $("#uploadFileList");
				var content = fileListValue+"<span id='fileList"+newFileName+"'><br/><a href=\"javascript:downLoadFile('"+data+"')\">"+oldFileName+"</a>&nbsp;&nbsp<img src='common/images/X.gif' onClick=\"deleteFile('"+newFileName+"')\" /></span>";
				obj.html(content);
			}
		},
	    error: function (data, status, e)             //相当于java中catch语句块的用法
	    {
	    	alert("上传文件失败!");
	    }
	});
}

/** 删除上传的文件 **/
function deleteFile(fileName){
	$.ajax({   
	    type : "post",   
	    url : "TestServlet?action=deleteFile",  
	    data : "fileName="+fileName,   
	    success:function(msg){
	  		alert(msg);
	  		if(msg == "删除成功!"){
	  			var t = "fileList"+fileName;
	  			var ttt = document.getElementById(t);
	  			ttt.innerHTML = "";
	  		}  
	    }
	}) 
}

/** 下载文件 **/
function downLoadFile(fileName){
	window.location.href = "TestServlet?action=downLoadFile&fileName="+encodeURIComponent(encodeURIComponent(fileName));
}
</script>
</head>
<body>
<form name="frm" id="frm"  method="POST" enctype="multipart/form-data">
<input type="file" name="fileC" id="fileC" style="width:400px;height:25px"/>
<input type="button" name="upload" id="upload" value="上传文件" onClick="uploadFile()"/>
<br/><span id="uploadFileList"></span>
</form>
</body>
</html>

?

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class TestServlet extends HttpServlet {
	public TestServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");// 设置编码方式,保证返回到前台中文不乱码
		request.setCharacterEncoding("UTF-8");// 设置编码方式,保证从前台到后台中文不乱码
		response.setCharacterEncoding("UTF-8");
		String action = request.getParameter("action");
		if (action.equals("upload")) {
			upload(request, response);
		} else if (action.equals("deleteFile")) {
			deleteFile(request, response);
		} else if(action.equals("downLoadFile")){
			downLoadFile(request, response);
		}
	}

	public void init() throws ServletException {
		// Put your code here
	}

	/**
	 * 上传文件
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void upload(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String result = "";
		try {
			result = UpFile(request);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "上传文件失败!";
		}
		System.out.println(result);
		response.getWriter().print(result);
	}

	/**
	 * 删除上传的文件
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void deleteFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String result = "";
		String fileName = request.getParameter("fileName");
		try {
			boolean b = false;
			b = deleteFileDao(fileName);
			if (b) {
				result = "删除成功!";
			} else {
				result = "删除失败!";
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "删除文件失败!";
		}
		response.getWriter().print(result);
	}
	
	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void downLoadFile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String fileName = java.net.URLDecoder.decode(request.getParameter("fileName"),"UTF-8");//后台转编码一次成中文
		String[] fileNameAll = fileName.split("\\|");
		String oldFileName = fileNameAll[0];
		String newFileName = fileNameAll[1];
		String filePath = this.getServletConfig().getServletContext().getRealPath("/");
		File file = new File(filePath + "uploaded\\" + newFileName);
		response.setContentType("application/x-msdownload");
		response.setContentLength((int) file.length());
		response.setHeader("Content-Disposition", "attachment;filename=" + new String(oldFileName.getBytes("GBK"), "ISO8859_1"));//保证另存为文件名为中文
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(fis);
		byte[] b = new byte[1024];
		long k = 0;

		OutputStream out = response.getOutputStream();
		while (k < file.length()) {
			int j = bis.read(b, 0, 1024);
			k += j;
			out.write(b, 0, j);
		}
		out.close();
		bis.close();
		fis.close();
	}


	/**
	 * 上传文件
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public String UpFile(HttpServletRequest req) throws Exception {// 上传文件
	// req.setCharacterEncoding("UTF-8");//设置编码方式,让上传的文件(中文)不会出现乱码
		String fileName = "";
		String filePath = this.getServletConfig().getServletContext()
				.getRealPath("/");
		File saveDir = new File(filePath + "uploaded");
		if (!saveDir.isDirectory()) {
			saveDir.mkdir();
		}
		DiskFileItemFactory dff = new DiskFileItemFactory();// 创建该对象
		dff.setRepository(saveDir);// 指定上传文件的临时目录
		dff.setSizeThreshold(1024000);// 指定在内存中缓存数据大小,单位为byte
		ServletFileUpload sfu = new ServletFileUpload(dff);// 创建该对象
		sfu.setSizeMax(50000000);// 指定单个上传文件的最大尺寸
		List items = sfu.parseRequest(req);// 解析request //
		// 请求,并返回FileItemIterator集合
		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			FileItem fis = (FileItem) iter.next();// 从集合中获得一个文件流
			if (!fis.isFormField()) {// 过滤掉表单中非文件域
				fileName = fis.getName().substring(
						fis.getName().lastIndexOf("\\") + 1);// 获得上传文件的文件名
				String hzm = fileName.substring(fileName.indexOf('.'));// 获取文件的后缀名
				String nameString = getNewFileName() + hzm;// 新生成的文件名称
				fis.write(new File(saveDir + "\\" + nameString));
				fileName = fileName + "|" + nameString;
			}
		}
		return fileName;
	}

	/**
	 * 删除文件
	 * 
	 * @param fileName
	 * @return
	 */
	public boolean deleteFileDao(String fileName) {
		boolean b = false;
		String filePath = this.getServletConfig().getServletContext()
				.getRealPath("/");
		File file = new File(filePath + "uploaded\\" + fileName);
		if (file.exists()) {
			file.delete();
			b = true;
		}
		return b;
	}

	/**
	 * 生成新文件名称(年月日时分秒+二位随机码)
	 * 
	 * @return
	 */
	public String getNewFileName() {
		String newFileName = "";
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyyMMddHHmmss");
		newFileName = simpleDateFormat.format(date);
		String random = getRandom(2);
		return newFileName + random;
	}

	/**
	 * 获取n位随机数
	 * 
	 * @param n
	 * @return
	 */
	public String getRandom(int n) {
		String randomString = "";
		if (n == 1) {
			randomString = (int) (Math.random() * 10) + "";
		} else {
			randomString = getRandom(n - 1) + (int) (Math.random() * 10);
		}
		return randomString;
	}
}

?

  相关解决方案