js 选择本地文件夹,上传文件夹
适用于IE浏览器,而且需要设置安全级别,ActiveX插件前3项为启用
1.html页面代码
<input type="text" id="FolderPath" name="FolderPath" size="20"/>
<input type="button" id="selectFolder" value="选择文件夹" />
2.js 代码
$('#selectFolder').click(function() {
try {
var Message = "\u8bf7\u9009\u62e9\u6587\u4ef6\u5939"; //选择框提示信息
var Shell = new ActiveXObject("Shell.Application");
//var Folder = Shell.BrowseForFolder(0, Message, 64, 17);//起始目录为:我的电脑
var Folder = Shell.BrowseForFolder(0,Message,0); //起始目录为:桌面
if (Folder != null) {
Folder = Folder.items(); // 返回 FolderItems 对象
Folder = Folder.item(); // 返回 Folderitem 对象
Folder = Folder.Path; // 返回路径
if (Folder.charAt(Folder.length - 1) != "\\") {
Folder = Folder + "\\";
}
document.getElementById('FolderPath').value = Folder;
return Folder;
}
}
catch (e) {
alert(e.message);
}
});
给id="FolderPath"的input复制
var folderpath = document.getElementById("FolderPath").value;
用其他字符替换掉斜杠/
folderpath = folderpath.replace(/\\/g,'-');
提交form表单
$('#formid').submit();
java代码把路径中的斜杠/替换回来
folderpath = folderpath.replaceAll("-", "/");
List<File> list = new ArrayList<File>();
List<File> fileList = blFile(list, folderpath);
/*
* 遍历文件夹
*/
private List<File> blFile(List<File> fileList,String path) {
File file = new File(path);
File[] files = file.listFiles();
if (files.length>0) {
for (File f : files) {
if (f.isFile()) {
fileList.add(f);
} else if (f.isDirectory()) {
blFile(fileList,f.getAbsolutePath());
}
}
}
return fileList;
}
/*
* 遍历FTP文件夹
*/
private List<FTPFile> blFTPFile(List<FTPFile> fileList,String path,PdeFtpClient client) throws IOException {
FTPFile[] ftpfile = client.listFiles(path);
if (ftpfile.length>0) {
for (FTPFile f : ftpfile) {
if (f.isFile()) {
fileList.add(f);
} else if (f.isDirectory()) {
blFTPFile(fileList,path+"/"+f.getName()+"/",client);
}
}
}
return fileList;
}
/*
* 获取后缀
*/
private String getExt(String str){
String ext = "";
if(str.contains(".")){
ext = str.substring(str.lastIndexOf(".")+1).toLowerCase();
}
return ext;
}
/**
* 删除单个文件
* @param sPath 被删除文件path
* @return 删除成功返回true,否则返回false
*/
public boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
/**
* 删除目录以及目录下的文件
* @param sPath 被删除目录的路径
* @return 目录删除成功返回true,否则返回false
*/
public boolean deleteDirectory(String sPath) {
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) break;
}else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) break;
}
}
if (!flag) return false;
if (dirFile.delete()) {
return true;
} else {
return false;
}
}