JavaScript Uploadify文件上传实例

前言

java+javascript,没用上数据库,做了一个简简单单的jsp上传小功能,就是记录一下,对于这个小项目有什么建议,欢迎指出不足之处 (-_+)

PS:从我的包名看得出,我用过很多前辈们的代码,基本上都是东凑西拼,各个部分代码的出处就不一一列出了,能看就行!

运行环境:

Java EE + Tomcat 7.0

项目结构
( Dynamic Web Project )

JavaScript Uploadify文件上传实例_第1张图片

src各部分代码

1. com.bijian.study.Upload.java

package com.bijian.study;

import java.io.File;
import java.io.IOException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.test.util.FileUtil;

@SuppressWarnings("serial")
public class Upload extends HttpServlet {

  private final String SEP = File.separator;
  private FileUtil fUtil = new FileUtil();

  @SuppressWarnings("unchecked")
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String savePath = this.getServletConfig().getServletContext()
        .getRealPath("");
    savePath = savePath + "/uploads/";

    File f1 = new File(savePath);
    System.out.println(savePath);
    if (!f1.exists()) {
      f1.mkdirs();
    }
    DiskFileItemFactory fac = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fac);
    upload.setHeaderEncoding("utf-8");

    String package_path = request.getParameter("save_path");
    String remark = request.getParameter("remark");

    List fileList = null;
    try {
      fileList = upload.parseRequest(request);
    } catch (FileUploadException ex) {
      return;
    }
    Iterator it = fileList.iterator();
    String name = "";
    String extName = "";
    String sysDate = "";
    String fileFrom = "";
    while (it.hasNext()) {
      FileItem item = it.next();
      if (!item.isFormField()) {
        long size = item.getSize();
        String type = item.getContentType();
        name = item.getName();
        if (name == null || name.trim().equals("")) {
          continue;
        }
        if (name.lastIndexOf(".") >= 0) {
          extName = name.substring(name.lastIndexOf("."));
        }
        File file = null;
        do {
          file = new File(savePath + name + extName);
        } while (file.exists());
        File saveFile = new File(savePath + name);
        fileFrom = saveFile.getAbsolutePath();
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
            "yyyy/MM/dd HH:mm:ss");
        sysDate = dateFormat.format(now);
        try {
          item.write(saveFile);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    remark = ChangeDeocode(remark);
    package_path = ChangeDeocode(package_path);

    String keep_path = "C:" +SEP+ package_path+SEP+name;
    String save_path = "C:" +SEP+ package_path;
    if(!fUtil.isFileExist(save_path)){
      fUtil.mkDir("C:" +SEP+ package_path);
    }

    fUtil.copyFile(fileFrom, keep_path);
    if(fUtil.isFileExist(keep_path)){
      fUtil.appendMethod(name + "|" + sysDate + "|" + remark+"|"+save_path);
    }
    response.getWriter().print(name + "\\" + sysDate + "\\" + remark);
  }


  public String ChangeDeocode(final String dataStr) {
    String ToDeocode = "";
    if (dataStr.contains("%")) {
      char[] charArray = dataStr.toCharArray();
      int ToChangeIndex = 0;

      for (int i = 0; i < charArray.length; i++) {
        if (i <= ToChangeIndex && i != 0) {
          continue;
        } else {
          if (charArray[i] == '%' && charArray[i + 1] == 'u'
              && i + 5 < charArray.length) {
            char[] tempArray = new char[] { charArray[i],
                charArray[i + 1], charArray[i + 2],
                charArray[i + 3], charArray[i + 4],
                charArray[i + 5] };
            ToDeocode += decodeUnicode(String.valueOf(tempArray));
            ToChangeIndex = i + 5;
          } else {
            ToDeocode += charArray[i];
            continue;
          }
        }
      }
    }
    return ToDeocode;
  }

  public String decodeUnicode(final String dataStr) {
    int start = 0;
    int end = 0;
    final StringBuffer buffer = new StringBuffer();
    while (start > -1) {
      end = dataStr.indexOf("\\u", start + 2);
      String charStr = "";
      if (end == -1) {
        charStr = dataStr.substring(start + 2, dataStr.length());
      } else {
        charStr = dataStr.substring(start + 2, end);
      }
      char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
      buffer.append(new Character(letter).toString());
      start = end;
    }
    return buffer.toString();
  }
}

2. com.test.tag.MyIteratorTag.java

package com.test.tag;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class MyIteratorTag extends TagSupport {

  private final String SEP = File.separator;
  private List files = null;
  private List data = null;
  private int columnSize = 0;

  @Override
  public int doStartTag() throws JspException {
    // TODO Auto-generated method stub

    JspWriter out = this.pageContext.getOut();
    StringBuffer sf = new StringBuffer();

    sf.append("");
    sf.append("");
    sf.append("");
    sf.append("
"); sf.append(""); if (this.data == null || this.data.isEmpty()) { sf.append(" "); sf.append(" "); sf.append(" "); } else { for (int i = 0; i < data.size(); i++) { String[] trs = data.get(i); sf.append(""); for (int j = 0; j < trs.length; j++) { switch (j) { case 0: sf.append(""); break; case 1: sf.append(""); break; case 2: sf.append(""); break; case 3: sf.append(""); break; default: sf.append(""); break; } } sf.append(""); } } sf.append("
"); sf.append(" No Valid Data List is NULL "); sf.append("
"); sf.append(""+trs[j]+""); sf.append(""); sf.append(""); sf.append("\t"+trs[j]); sf.append(""); sf.append("��"); sf.append(""); sf.append(""); sf.append(""); sf.append(""); sf.append("
"); sf.append("
"); sf.append(""); if(this.files != null && !this.files.isEmpty()){ for (int i = 0; i < files.size(); i++) { String[] trs = files.get(i); sf.append(""); for (int j = 0; j < trs.length; j++) { sf.append(""); } sf.append(""); sf.append(""); } } sf.append("
"); sf.append("\t"+trs[j]); sf.append(""); sf.append(""); // System.out.println("trs["+i+"]"+trs[i]); sf.append("
"); sf.append("
"); try { out.print(sf.toString()); } catch (IOException e) { e.printStackTrace(); throw new JspException(e.getMessage()); } return super.doEndTag(); } public List getfiles() { return files; } public void setfiles(List files) { this.files = files; } public List getData() { return data; } public void setData(List data) { this.data = data; } public int getColumnSize() { return columnSize; } public void setColumnSize(int columnSize) { this.columnSize = columnSize; } }

3. com.test.util.FileStringUtil.java

package com.test.util;

import java.util.HashMap;
import java.util.Map;

public class FileStringUtil {

  public Map getFileDetails(String fileString){
    Map detailMap = new HashMap<>();
    String[] splitStr = fileString.split("\\|");
    for (int i = 0; i < splitStr.length; i++) {
      detailMap.put("fileDetail"+i, splitStr[i]);
    }
    return detailMap; 
  }
}

4. com.test.util.FileUtil.java

package com.test.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.apache.catalina.authenticator.SavedRequest;


public class FileUtil {

  private final String SEP = File.separator;
  int count = 0;


  public static String [] getFileName(String path){ 
    File file = new File(path); 
    String [] fileName = file.list(); 
    return fileName; 
  }

  public boolean isFileExist(String path) {
    try {
      File file = new File(path);
      return file.exists();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return false;
  }

  public boolean mkDir(String path) {
    File dir = new File(path);
    boolean res = dir.mkdirs();
    return res;
  }

  public List readTxtFile(String filePath) {
    List resultList = new ArrayList<>();
    try {
      String encoding = "UTF-8";
      File file = new File(filePath);
      if (file.isFile() && file.exists()) { // 判断文件是否存在
        InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
        BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt = null;
        while ((lineTxt = bufferedReader.readLine()) != null) {
          if(lineTxt.length() < 2){
            continue;
          }else {
            resultList.add(lineTxt);
          }
        }
        read.close();
      } else {
        System.out.println("找不到指定的文件");
      }
    } catch (Exception e) {
      System.out.println("读取文件内容出错");
      e.printStackTrace();
    }
    return resultList; 
  }


  public List readTxtFileByPath(String filePath,String Path) {
    String savePath = "c:\\"+Path;
    List resultList = new ArrayList<>();
    try {
      String encoding = "UTF-8";
      File file = new File(filePath);
      if (file.isFile() && file.exists()) { // 判断文件是否存在
        InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
        BufferedReader bufferedReader = new BufferedReader(read);
        String lineTxt = null;
        int lineNumber = 0;
        while ((lineTxt = bufferedReader.readLine()) != null) {
          lineNumber++;
          System.out.println("lineNumber "+lineNumber);
          if(lineTxt.length() < 2){
            continue;
          }else {
            String lastRead = lineTxt.substring(lineTxt.lastIndexOf("|")+1,lineTxt.length());
            String fristRead = lineTxt.substring(0,lineTxt.indexOf("|"));
            if(lastRead.toUpperCase().equals(savePath.toUpperCase())){

              File savePathFile = new File(savePath);
              File[] files = savePathFile.listFiles();

              if(files.length == 0){//��文件�A所有文件不存在�r
                lineTxt = "";
                System.out.println("none file of "+savePath);
              }else {
                boolean fileDelete = true;
                for (int i = 0; i < files.length; i++) {
                  System.out.println("files" + files[i].getName());
                  System.out.println("fristRead"+fristRead);
                  if(fristRead.equals(files[i].getName())){
                    //��文件列表中存在一�t��文件名�c列表文件名匹配�r,�C明文件�]有被�h除
                    fileDelete = false;
                  }
                }
                if (fileDelete) {
                  //文件是否被�h除,是:�h除��l��;否:������存留
                  deleteLineText(lineNumber);
                }else {
                  resultList.add(lineTxt);
                }
              }        
            }
          }

        }
        read.close();
      } else {
        System.out.println("找不到指定的文件");
      }
    } catch (Exception e) {
      System.out.println("读取文件内容出错");
      e.printStackTrace();
    }
    return resultList; 
  }


  public void deleteLineText(int lineNum){
//   BufferedReader br;
    try {
//     br = new  BufferedReader(new FileReader("c:/a.txt "));
      BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\a.txt"),"UTF-8")); 
      StringBuffer sb=new StringBuffer(4096);
      String temp=null;
      int  line=0;

      while((temp=br.readLine())!=null){
          line++;
          if(line==lineNum)  
            continue;
          sb.append(temp).append("\r\n");
//         sb.append(new String(temp.getBytes("Unicode"), "UTF-8")).append( "\r\n ");
      }
      br.close();
      OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream("c:/a.txt "),"UTF-8");   
      BufferedWriter writer=new BufferedWriter(write); 
//     BufferedWriter  bw=new  BufferedWriter(new FileWriter( "c:/a.txt "));
      writer.write(sb.toString());
      writer.close();
    } catch (FileNotFoundException e) {
      System.out.println(e.toString());
      e.printStackTrace();
    } catch (IOException e) {
      System.out.println(e.toString());
      e.printStackTrace();
    }

  }


  public void writeTxtFile(File file, String fileContent)  
  {   
    try  
    {   
      OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");   
      BufferedWriter writer=new BufferedWriter(write); 
      writer.write(fileContent);   
      writer.close();   
    } catch (Exception e)  
    {   
      e.printStackTrace();   
    } 
  }


  public int[] getAllFileSize(String[] filePath){
    int[] fileSizeArray = new int[filePath.length];
    for (int i = 0; i < filePath.length; i++) {
      if(!isFileExist("c:\\"+filePath[i])){
        mkDir("c:\\"+filePath[i]);
      }
      File file = new File("c:\\"+filePath[i]);
      File[] files = file.listFiles();
      fileSizeArray[i] = files.length;
    }
    return fileSizeArray;

  }

  public String deleteFile(){
    String result = "";
    if(count == 0){
      System.out.println("0");
      result = "0";
    }else {
      System.out.println("deleteFile");
      result = "deleteFile";
    }
    count++;
    return result;
  }

  public void appendMethod(String content) {

    try {
      File file = new File("C:\\a.txt");
      if (!file.exists()){    
         file.createNewFile();
        writeTxtFile(file,content);
      }else {
       Writer out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream("C:\\a.txt",true),"UTF-8"));
       out.write("\r\n"+content);
       out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  public static boolean copyFile(String fromFile, String toFile) {
    try {
      InputStream fosfrom = new FileInputStream(fromFile);
      OutputStream fosto = new FileOutputStream(toFile);
      byte bt[] = new byte[4096];
      int c;
      while ((c = fosfrom.read(bt)) > 0) {
        fosto.write(bt, 0, c);
      }
      fosfrom.close();
      fosto.close();
      bt = null;
      return true;

    } catch (Exception ex) {
      ex.printStackTrace();
      return false;
    }
  }  
}

web.xml配置

 
 

  
  upload 
  com.bijian.study.Upload 
  

  
  upload 
  /servlet/Upload 
  

  
  index.jsp 
  


 

  
 my-taglib
 
 /WEB-INF/my-taglib.tld
  
 
 

index.jsp

<%@page import="org.apache.tomcat.jni.File"%>
<%@ page language="java" contentType="text/html; charset=utf-8" import="java.util.*" import="com.test.util.*"%> 
<%@ taglib uri="my-taglib" prefix="myTag"%>
<% 
  String path = request.getContextPath(); 
  String basePath = request.getScheme() + "://" 
      + request.getServerName() + ":" + request.getServerPort() 
      + path + "/"; 

  int SHOW_CONTROL = 0;

  final String RECORED_PATH = "c:\\a.txt";
  String getParameter = request.getParameter("num");
  if(getParameter !=null){
    System.out.println("getParameter "+getParameter);
    SHOW_CONTROL = Integer.parseInt(getParameter);
  }else{
    SHOW_CONTROL = 0;
  }


  List data = new ArrayList();
  String data1[] = new String[]{"相片","代工�","其他","��r��","�D�t"};
  int data2[] = new FileUtil().getAllFileSize(data1);
  for(int i = 0;i fileList = new FileUtil().readTxtFileByPath(RECORED_PATH,data1[SHOW_CONTROL]);
  int FILE_SIZE = fileList.size(); 
  int fileID[] = new int[FILE_SIZE];
  String fileName[] = new String[FILE_SIZE];
  String fileDate[] = new String[FILE_SIZE];
  String fileRemark[] = new String[FILE_SIZE];


  for(int i=0;i map =new FileStringUtil().getFileDetails(fileList.get(i));
     fileID[i] = i+1;
     fileName[i] = map.get("fileDetail0");
     fileDate[i] = map.get("fileDetail1");
     fileRemark[i] = map.get("fileDetail2");
     files.add(new String[]{fileID[i]+"",fileName[i],fileDate[i],fileRemark[i],""});
  }

  request.setAttribute("data" ,data);
  request.setAttribute("files" ,files);
%> 
 
 
 
 
Upload 

 
 


 
 

 
 
 

 

 

 


至此,这个小项目就写到这里,下面是Demo连接

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(JavaScript Uploadify文件上传实例)