1. 文档上传的一个简单界面 docUpload.jsp:
- <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'docUpload.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
- -->
-
- <mce:script type="text/javascript" src="resources/jquery.js" mce_src="resources/jquery.js"></mce:script>
- <mce:script type="text/javascript" src="resources/upload/fileUploadUtil.js" mce_src="resources/upload/fileUploadUtil.js"></mce:script>
- <mce:script type="text/javascript" src="resources/ajaxfileupload.js" mce_src="resources/ajaxfileupload.js"></mce:script>
-
- </head>
-
- <mce:script type="text/javascript"><!--
-
-
- var uploadFileSize = "100000000";
-
- $(document).ready(function(){
- $("#test").click(function(){
- uploadFile();
- });
- });
-
-
-
- <body>
- <form action="#">
- <table id="upload" border="1">
- <tr>
- <td width="20%">序号</td>
- <td width="30%">名字</td>
- <td width="50%">路径</td>
- <td width="20%">状态</td>
- </tr>
- <tr>
- <td>1</td>
- <td>111</td>
- <td><input type="file" name="newfile" onchange="checkFile(this);"></input></td>
- <td><p id="flag1">正常</p></td>
- </tr>
- </table>
-
- <input type="submit" value="确定" id="test"></input>
- </form>
- </body>
- </html>
2. fileUploadUtil.js 为上传下载文档都需要引入的JS
-
-
-
- var uploadFileSize = "";
- var checkFileFlag = false;
- var fileCount = -1;
- var paramterUrl = "";
-
-
- function uploadFile() {
-
-
- if(checkFileFlag == false) {
- checkFileFlag = true;
- var flag = checkFilePath();
- if(flag) {
- alert("/u6587/u4ef6/u5730/u5740/u4e0d/u80fd/u4e3a/u7a7a!");
- checkFileFlag = false;
- return;
- }
- }
-
- fileCount++;
- var fileId = "";
- var filePath = "";
-
-
- $(":file[id*='uploadFileName']").each(function(i){
- if(i == fileCount) {
- fileId = $(this).attr("id");
- filePath = $(this).val();
- }
- });
-
- if(filePath == null || filePath == "") {
- return;
- } else {
- $("p[id*='showName']").each(function(i){
- if(i == fileCount) {
- $(this).text("/u6587/u4ef6/u4e0a/u4f20/u4e2d/u3002/u3002/u3002/u3002/u3002");
- $("#test").attr("disabled","disabled");
-
- doUploadFile(filePath,fileId);
- }
- });
- }
- }
-
-
-
-
-
- function doUploadFile(filePath,fileId) {
-
-
- var paths = filePath.split("//");
- var fileName = paths[paths.length - 1];
-
-
-
-
- var url = "/AJAX/servlet/FileUploadServlet?" + "name=linwei1111";
- url = encodeURI(encodeURI(url));
-
-
-
- $.ajaxFileUpload({
- type:"POST",
- secureuri:false,
-
- fileElementId:fileId,
- dataType:"json",
- url: url,
-
- success:function(data){
- if(data.status == "success") {
- $("p[id*='showName']").each(function(i){
- if(i == fileCount) {
- $(this).text("/u4e0a/u4f20/u6210/u529f");
- }
- });
- } else {
- $("p[id*='showName']").each(function(i){
- if(i == fileCount) {
- $(this).text("/u4e0a/u4f20/u5931/u8d25");
- }
- });
- }
- gotoNextUpload();
- },
- error:function(xhr,status,err) {
- alert("/u51fa/u9519/u4e86/u3002");
- gotoNextUpload();
- }
- });
- }
-
-
- /**
- * 跳转到下一个页面,判断是否继续上传文档
- */
- function gotoNextUpload() {
-
- var size = $(":file[id*='uploadFileName']").size();
-
- if(fileCount<size-1) {
- uploadFile();
- } else {
- $("#test").removeAttr("disabled");
- }
- }
-
-
-
-
-
- function checkFilePath() {
-
- var flag = false;
- $("input[name*='a']").each(function(i){
- if($(this).val() == null || $(this).val() == "") {
- flag = true;
- return flag;
- }
- });
- return flag;
- }
-
-
-
-
- function checkFile(obj) {
-
-
- if(obj.value.length>0) {
-
- var af = "jpg,gif,png,zip,rar,txt,doc,htm,pdf,xls";
-
- if (eval("with(obj.value)if(!/" + af.split(",").join("|")
- + "/ig.test(substring(lastIndexOf('.')+1,length)))1;")) {
-
- alert("/u5141/u8bb8/u4e0a/u4f20/u7684/u6587/u6863/u7c7b/u578b/u4e3a:/n" + af);
-
- obj.outerHTML = obj.outerHTML;
- } else {
- checkFileSize(obj);
- }
- }
- }
-
-
-
-
- function checkFileSize(obj) {
-
- if (!getFileSize(obj.value)) {
- obj.outerHTML = obj.outerHTML;
- alert("/u4e0a/u4f20/u6587/u4ef6/u5927/u5c0f/u8bf7/u52ff/u5927/u4e8e"+parseInt(Number(uploadFileSize)/(1000*1000))+"M");
- }
- }
-
-
-
-
- function getFileSize(filePath) {
-
- var fileSize = "-1";
-
-
-
- var image = new Image();
- image.dynsrc = filePath;
- fileSize = image.fileSize;
-
-
-
-
-
-
-
- if(Number(fileSize)<Number(uploadFileSize)) {
- return true;
- } else {
- return false;
- }
- }
-
-
-
-
-
-
- $(document).ready(function(){
-
-
- $(":file").each(function(i){
- var thisFileId = i + "uploadFileName";
-
- $(this).attr("id",thisFileId);
- });
-
-
- $("p[id*='flag']").each(function(i){
- var thisShowId = i + "showName";
-
- $(this).attr("id",thisShowId);
- });
-
-
-
- });
-
-
-
-
- function doFileDown(id) {
-
- var url = "http://localhost:8080/AJAX/servlet/fileDownload?id=" + id;
- $("#" + id).attr("href",url);
- $("#" + id).click(function(){
- alert($(this).attr("href"));
- });
-
- }
3. FileUploadServlet.java 是上传的Servlet
4. FileOperation.java 是文档的操作类
- package upload;
-
- import java.io.BufferedReader;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
-
- import javax.servlet.http.HttpServletRequest;
-
- import org.apache.commons.fileupload.DiskFileUpload;
- import org.apache.commons.fileupload.FileItem;
-
- import doc.util.ZipUtil;
-
-
-
-
-
-
-
- public class FileOperation {
-
-
-
-
-
-
-
- public DocumentVO doWriteFile(HttpServletRequest request) throws Exception {
-
-
-
- DiskFileUpload diskFileUpload = new DiskFileUpload();
-
- diskFileUpload.setSizeMax(new Long(102400000));
-
- diskFileUpload.setSizeThreshold(4096);
-
- diskFileUpload.setHeaderEncoding("GBK");
-
- diskFileUpload.setHeaderEncoding("gb2312");
-
-
-
- List fileItem = diskFileUpload.parseRequest(request);
-
- if(fileItem.size() == 0) {
- System.out.println("数量为0.");
- }
-
-
- Iterator it = fileItem.iterator();
-
- List list = null;
- Map map = null;
- DocumentVO documentVO = null;
- File file = null;
- while(it.hasNext()) {
- FileItem fi = (FileItem)it.next();
-
- InputStream in = fi.getInputStream();
-
- if(in == null) {
- System.out.println("流是空的。");
- }
-
-
-
- if(!fi.isFormField()) {
- list = new ArrayList();
- map = new HashMap();
-
- String filePath = fi.getName();
- String fileName = this.getFileName(filePath);
- String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
- fileName = fileName.substring(0,fileName.lastIndexOf("."));
- documentVO = new DocumentVO();
- documentVO.setFileName(fileName);
- documentVO.setFileType(fileType);
- documentVO = this.getSequenceNumber(documentVO);
-
- System.out.println("fileName is " + fileName);
- list.add(in);
-
-
-
-
-
-
- }
- }
-
-
- return this.upload(documentVO, list);
- }
-
-
-
-
-
-
-
-
- private DocumentVO upload(DocumentVO documentVO,List list) throws Exception {
-
- if(documentVO == null || "".equals(documentVO)) {
- throw new Exception("documentVO 不能为空!");
- }
-
- if(list == null || list.size() == 0) {
- throw new Exception("没有文件流。");
- }
-
- InputStream in = (InputStream)list.get(0);
- return this.transferDocument(documentVO, in);
- }
-
-
-
-
-
-
-
-
- private DocumentVO transferDocument(DocumentVO documentVO,Object bytesStream) {
-
-
- String path = "D://Workspace//DocumentUpload//";
-
-
- String fileAbsolutePath = path + documentVO.getSequenceNumber();
-
- if(bytesStream instanceof InputStream) {
-
- ZipUtil zipUtil = new ZipUtil();
- Map map = new HashMap();
-
- map.put(documentVO.getFileName()+"."+documentVO.getFileType(), (InputStream)bytesStream);
- try {
- zipUtil.zip(fileAbsolutePath, map);
- System.out.println("OK");
- } catch (Exception e) {
-
- e.printStackTrace();
-
- this.write((InputStream)bytesStream, fileAbsolutePath,documentVO);
- }
- } else {
- this.write((OutputStream)bytesStream, fileAbsolutePath,documentVO);
- }
-
-
- return documentVO;
- }
-
-
- /**
- * 取得存储时候的文件名,最后也是根据这个名字去数据库中查询的
- * @param fileName
- * @return
- */
- private DocumentVO getSequenceNumber(DocumentVO documentVO) {
-
-
- Calendar c = Calendar.getInstance();
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
- documentVO.setSequenceNumber(dateFormat.format(c.getTime()));
- return documentVO;
- }
-
-
-
-
-
-
-
- private String getFileName(String filePath) {
-
- int pos = filePath.lastIndexOf(File.separator);
-
- if(pos > 0) {
-
- return filePath.substring(pos + 1);
- } else {
- return filePath;
- }
- }
-
-
-
-
-
-
- public void write(InputStream in,String absolutePath,DocumentVO documentVO) {
-
- FileOutputStream file = null;
-
- try {
-
- this.checkFile(new File(absolutePath));
- absolutePath = absolutePath + "//" + documentVO.getFileName() + "." + documentVO.getFileType();
- file = new FileOutputStream(absolutePath);
-
- int length = 0;
- byte[] buffer = new byte[10240];
-
- while ((length = in.read(buffer, 0, 10240)) > -1) {
- file.write(buffer, 0, length);
- }
-
- } catch (FileNotFoundException e) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- } finally {
-
- try {
- if (in != null)
- in.close();
- if (file != null)
- file.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- }
-
-
-
-
-
- public void write(OutputStream out,String absolutePath,DocumentVO documentVO) {
-
- FileOutputStream file = null;
-
- try {
-
- this.checkFile(new File(absolutePath));
- absolutePath = absolutePath + "//" + documentVO.getFileName() + "." + documentVO.getFileType();
- file = new FileOutputStream(absolutePath);
- ByteArrayOutputStream baos = (ByteArrayOutputStream)out;
- file.write(baos.toByteArray());
-
- } catch (FileNotFoundException e) {
-
- e.printStackTrace();
- } catch (IOException e) {
-
- e.printStackTrace();
- } finally {
-
- try {
- if (out != null)
- out.close();
- if (file != null)
- file.close();
- } catch (IOException e) {
-
- e.printStackTrace();
- }
- }
- }
-
-
-
-
-
-
-
-
- private void checkFilePath(File file) {
- this.checkFile(file.getParentFile());
- }
-
-
-
-
-
-
-
- private void checkFile(File file) {
-
- if(!file.exists()) {
-
- this.checkFilePath(file.getParentFile());
- file.mkdir();
- }
- }
-
-
-
-
-
-
-
- public void logSequenceNumber(DocumentVO documentVO) throws Exception {
-
- if(documentVO != null && !"".equals(documentVO)) {
- if(documentVO.getSequenceNumber() != null && !"".equals(documentVO.getSequenceNumber())) {
-
- String sequenceNumber = documentVO.getSequenceNumber() + ",";
- this.logSeqToFile(sequenceNumber);
- }
- }
- }
-
-
-
-
-
-
-
- private void logSeqToFile(String sequenceNumber) throws IOException {
-
-
- String path = "D://Workspace//DocumentUpload//node.txt";
- File file = new File(path);
- FileOutputStream out = new FileOutputStream(file,true);
- byte[] byte1 = new byte[512];
- int b = sequenceNumber.length();
-
- out.write(sequenceNumber.getBytes());
- out.close();
- }
-
-
-
-
-
-
-
-
- public String getLogFile() throws Exception {
-
- String str = "";
-
- String path = "D://Workspace//DocumentUpload//node.txt";
- File file = new File(path);
- BufferedReader b = new BufferedReader(new FileReader(file));
- String i;
- while((i = b.readLine()) != null) {
- str += i;
- }
- return str;
- }
-
-
-
- }
5. 文档压缩类 ZipUtil
- package doc.util;
-
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
-
- import org.apache.tools.zip.ZipEntry;
- import org.apache.tools.zip.ZipOutputStream;
-
-
-
-
-
-
-
- public class ZipUtil {
-
-
- public final static long maxSize = 100000000;
- public final static int BUFFERSIZE = 2048 ;
- private static final ThreadLocal currentZipName = new ThreadLocal();
-
-
-
-
-
-
-
-
- public void zip(String fileOutPath, Map mapInputStreams) throws Exception {
-
- if (fileOutPath == null || "".equals(fileOutPath)) {
- return;
- }
-
- if (mapInputStreams != null && mapInputStreams.size() > 0) {
- Set entrys = mapInputStreams.entrySet();
- FileOutputStream out = new FileOutputStream(fileOutPath);
-
- ZipOutputStream zip = new ZipOutputStream(out);
- String fileName = null;
- InputStream inputStream = null;
- Iterator it = entrys.iterator();
- while (it.hasNext()) {
- Map.Entry entry = (Map.Entry) it.next();
- fileName = (String) entry.getKey();
- inputStream = (InputStream) entry.getValue();
- zip(zip, inputStream, fileName);
- }
- zip.close();
- }
- }
-
-
-
-
-
-
-
-
-
- private void zip(ZipOutputStream out, InputStream inputStream,
- String fileName) throws Exception {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- out.putNextEntry(new org.apache.tools.zip.ZipEntry(fileName));
- int b1;
- byte[] buf1 = new byte[BUFFERSIZE];
- while ((b1 = inputStream.read(buf1)) != -1) {
- out.write(buf1, 0, b1);
- }
- if (inputStream != null) {
- inputStream.close();
- inputStream = null;
- }
- }
- }
6. 文档的实体类 DocumentVO
- package upload;
-
-
-
-
-
-
-
- public class DocumentVO {
-
- private String fileName;
- private String sequenceNumber;
- private String fileType;
-
- public String getFileName() {
- return fileName;
- }
-
- public void setFileName(String fileName) {
- this.fileName = fileName;
- }
-
- public String getSequenceNumber() {
- return sequenceNumber;
- }
-
- public void setSequenceNumber(String sequenceNumber) {
- this.sequenceNumber = sequenceNumber;
- }
-
- public String getFileType() {
- return fileType;
- }
-
- public void setFileType(String fileType) {
- this.fileType = fileType;
- }
-
- }
7. 文档调阅界面
- <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
- <%@ page import="upload.*" %>
-
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
-
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
-
- <title>My JSP 'docUpload.jsp' starting page</title>
-
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
- -->
-
- <mce:script type="text/javascript" src="resources/jquery.js" mce_src="resources/jquery.js"></mce:script>
- <mce:script type="text/javascript" src="resources/upload/fileUploadUtil.js" mce_src="resources/upload/fileUploadUtil.js"></mce:script>
-
- </head>
-
-
- <body>
- <%
- FileOperation f = new FileOperation();
- String str = f.getLogFile();
- String[] s = str.split(",");
- %>
- <form action="" name="form1">
- <table id="upload" border="1">
- <tr>
- <td width="20%">文档连接</td>
- </tr>
- <%
- for(int i=0;i<s.length;i++) {
-
- %>
- <tr>
- <td><a href="/AJAX/servlet/fileDownload?id=<%=s[i]%>"><%=s[i] %></a></td>
- </tr>
- <%
- }
- %>
- </table>
- </form>
- </body>
- </html>
8. 调阅Servlet
- package upload;
-
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
-
- import javax.servlet.ServletException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
-
-
-
-
-
-
- public class fileDownload extends HttpServlet {
-
-
-
-
- public fileDownload() {
- super();
- }
-
-
-
-
- public void destroy() {
- super.destroy();
-
- }
-
-
-
-
-
-
-
-
-
-
-
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- System.out.println("doGet");
- this.doDownload(request, response);
- }
-
-
-
-
-
-
-
-
-
-
-
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- System.out.println("doPost");
- this.doDownload(request, response);
- }
-
-
-
-
-
-
- public void init() throws ServletException {
-
- }
-
-
-
-
-
-
-
-
-
- public void doDownload(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
-
- InputStream in = null;
-
- response.setContentType("application/x-download; charset=gb2312");
-
- String file_separator = System.getProperty( "file.separator" );
-
- String displayname = "temp111.zip";
-
- String path = "D://Workspace//DocumentUpload//" + request.getParameter("id");
- response.addHeader("Content-Disposition","attachment;filename=" + new String(displayname.getBytes("gb2312"),"iso-8859-1"));
-
- try {
- in = new FileInputStream(path);
- this.downLoad(in, response);
- } catch(Exception e) {
-
- } finally {
- if(in != null)
- in.close();
- }
- }
-
-
-
-
-
-
-
-
- private void downLoad(InputStream in, HttpServletResponse response) throws Exception {
-
- BufferedInputStream bufferInput = new BufferedInputStream(in);
- ServletOutputStream out = null;
-
- try {
- byte[] buffer = new byte[10240];
- out = response.getOutputStream();
- int len;
- while((len = bufferInput.read(buffer)) != -1) {
- out.write(buffer, 0, len);
- }
- out.flush();
- response.setStatus(response.SC_OK);
- response.flushBuffer();
- } catch(Exception e) {
- throw e;
- } finally {
- if (out != null) {
- out.close();
- }
- if (bufferInput != null) {
- bufferInput.close();
- }
- if (in != null) {
- in.close();
- }
- }
- }
- }
以上只是一些简单的过程,具体的一些信息还是需要按照不同的需求进行修改的。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。