前言
java+javascript,没用上数据库,做了一个简简单单的jsp上传小功能,就是记录一下,对于这个小项目有什么建议,欢迎指出不足之处 (-_+)
PS:从我的包名看得出,我用过很多前辈们的代码,基本上都是东凑西拼,各个部分代码的出处就不一一列出了,能看就行!
运行环境:
Java EE + Tomcat 7.0
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("");
if (this.data == null || this.data.isEmpty()) {
sf.append(" ");
sf.append(" ");
sf.append(" No Valid Data List is NULL ");
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("");
sf.append(""+trs[j]+"");
sf.append("");
sf.append(" ");
break;
case 1:
sf.append("");
sf.append("\t"+trs[j]);
sf.append(" ");
break;
case 2:
sf.append("");
sf.append("張");
sf.append(" ");
break;
case 3:
sf.append("");
sf.append("");
sf.append(" ");
break;
default:
sf.append("");
sf.append("");
sf.append(" ");
break;
}
}
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("\t"+trs[j]);
sf.append(" ");
}
sf.append("");
sf.append("");
// System.out.println("trs["+i+"]"+trs[i]);
sf.append(" ");
sf.append(" ");
}
}
sf.append("
");
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){//當文件夾所有文件不存在時
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())){
//當文件列表中存在一則記錄文件名與列表文件名匹配時,證明文件沒有被刪除
fileDelete = false;
}
}
if (fileDelete) {
//文件是否被刪除,是:刪除該條記錄;否:記錄應當存留
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配置
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>uploadservlet-name>
<servlet-class>com.bijian.study.Uploadservlet-class>
servlet>
<servlet-mapping>
<servlet-name>uploadservlet-name>
<url-pattern>/servlet/Uploadurl-pattern>
servlet-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<jsp-config>
<taglib>
<taglib-uri>my-taglibtaglib-uri>
<taglib-location>/WEB-INF/my-taglib.tldtaglib-location>
taglib>
jsp-config>
web-app>
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[]{"相片","代工紙","其他","報價單","圖則"};
int data2[] = new FileUtil().getAllFileSize(data1);
for(int i = 0;inew String[]{data1[i],data2[i]+"","",""});
}
List files = new ArrayList();
List<String> 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;iString,String> 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);
%>
<html>
<head>
<base href="<%=basePath%>">
<title>Uploadtitle>
<link href="css/uploadify.css" rel="stylesheet" type="text/css" />
<link href="css/Regist.css" type="text/css" />
<link href="css/jquery.ui.all.css" rel="stylesheet">
<script type="text/javascript" src="uploadify/jquery-1.9.1.js">script>
<script type="text/javascript" src="uploadify/jquery.uploadify.min.js">script>
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
'method':'get',
'uploader' : 'servlet/Upload',
'swf' : 'uploadify/uploadify.swf',
'cancelImg' : 'img/uploadify-cancel.png',
'folder' : 'uploads',//您想将文件保存到的路径
'queueID' : 'fileQueue',//与下面的id对应
'queueSizeLimit' : 5,
'fileDesc' : 'rar文件或zip文件',
'fileExt' : '*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc
'auto' : false,
'multi' : false,
'uploadLimit' : 10,
'buttonText' : '選擇檔案',
'removeCompleted':false,
onUploadStart: function(file) {
$('#uploadify').uploadify(
'settings', 'formData', {
'save_path': escape(document.getElementById("save_type_select").options[document.getElementById("save_type_select").selectedIndex].value),
'remark':escape(document.getElementById("remark").value)
});}
,
onUploadSuccess: function (file, data, response) {
window.location.reload();
}
});
});
function ReStartJSP(num){
location.replace("http://localhost:8080/uploadifyTest/index.jsp?num="+num);
}
function onload(){
initOptions();
ReadTxtFile();
}
function initOptions(){
// alert(isNaN(parseInt(size)));
var num = <%=data1.length%>;
for(var i = 0;ivar optionText = document.getElementById("hidden_"+i).value;
document.getElementById("save_type_select").add(new Option(optionText,optionText));
}
}
function setOptions(obj){
var SelectObj = document.getElementById("save_type_select");
SelectObj.options[parseInt(obj.value)].selected = true;
}
function showDIV(obj){
var div = document.getElementById("fileUploadDIV");
if(div.style.display == "none"){
div.style.display = "block";
}
setOptions(obj);
}
function hindDIV(){
var div = document.getElementById("fileUploadDIV");
if(div.style.display == "block"){
div.style.display = "none";
}
}
function deleteFile(name){
var showMessage = "c:\\"+"<%=data1[SHOW_CONTROL]%>"+"\\"+name;
var fso = new ActiveXObject("Scripting.FileSystemObject");
if(fso.FileExists(showMessage)){
fso.DeleteFile(showMessage);
alert("delete success!!");
location.replace("http://localhost:8080/uploadifyTest/index.jsp?num="+<%=SHOW_CONTROL%>);
}
}
script>
head>
<body onload="onload()">
<myTag:iter columnSize="4" files="${files}" data="${data}" />
br>br>br>
<div id="fileUploadDIV" style="display:none">
<table id="upload_table" >
<tr>
<td><select id="save_type_select">select>td>
<td><input type="file" name="uploadify" id="uploadify"/> td>
<td><label>備註:label ><input type="text" width="100px" id="remark" value='maah%e4u5848在哪呢你5874'/>td>
<td><a href="javascript:$('#uploadify').uploadify('upload');" style="font-size:14px;font-weight:normal">上載a>td>
<td><a href="javascript:$('#uploadify').uploadify('cancel'); hindDIV()" style="font-size: 14px; font-weight: normal">取消a>td>
tr>
table>
<div id="fileQueue" >div>
div>
body>
html>
至此,这个小项目就写到这里,下面是Demo连接
戳我戳我!