Commit 6f0c05b3 by 罗胜

漏洞问题处理

parent 915254dc
......@@ -83,7 +83,7 @@
<a href="${ctx}/airline/verify/list"><input id="btnCancel" class="btn" type="button" value="返回" /></a> </div>
</form:form>
<form style="display:none" id="form" action="dynamicFields.action?method=uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>
<%--<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>--%>
<input type="submit" value="确认提交">
</form>
......
......@@ -12,20 +12,20 @@
<script type="text/javascript">
$(document).ready(function() {
$("#no").focus();
$.get("${ctx}/airline/contacts/departData", null, function(data) {
if (!!data) {
var html = " ";
for (var i = 0; i < data.length; i ++) {
if(data[i].id!=null){
html += "<option value='" + data[i].id + "'>" + data[i].departName + "</option>"
}
}
var domParser = new DOMParser();
var doc = domParser.parseFromString(html, 'text/html');
$("#depart").innerHTML(doc);
}
$("#depart").select2().val("${userProfileEntity.departId}").trigger("change");
});
<%--$.get("${ctx}/airline/contacts/departData", null, function(data) {--%>
<%--if (!!data) {--%>
<%-- var html = " ";--%>
<%-- for (var i = 0; i < data.length; i ++) {--%>
<%-- if(data[i].id!=null){--%>
<%-- html += "<option value='" + data[i].id + "'>" + data[i].departName + "</option>"--%>
<%-- }--%>
<%-- }--%>
<%-- var domParser = new DOMParser();--%>
<%-- var doc = domParser.parseFromString(html, 'text/html');--%>
<%-- $("#depart").innerHTML(doc);--%>
<%--}--%>
<%--$("#depart").select2().val("${userProfileEntity.departId}").trigger("change");--%>
<%--});--%>
$("#inputForm").validate({
rules: {
loginName: {remote: "${ctx}/sys/user/checkLoginName?oldLoginName=" + encodeURIComponent('${userProfileEntity.loginName}')},
......
......@@ -58,7 +58,7 @@
<div id="importBox" class="hide">
<form id="importForm" action="${ctx}/airline/verify/import" method="post" enctype="multipart/form-data"
class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');"><br/>
<input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>
<%-- <input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>--%>
<input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 导 入 "/>
<a href="${ctx}/airline/verify/import/template">下载模板</a>
</form>
......@@ -157,7 +157,7 @@
</table>
<div class="pagination">${page}</div>
<form style="display:none" id="form" action="dynamicFields.action?method=uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>
<%--<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>--%>
<input type="submit" value="确认提交">
</form>
......
......@@ -74,7 +74,7 @@
<form id="importForm" action="${ctx}/airline/verify/import" method="post" enctype="multipart/form-data"
class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');">
<br/>
<input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>
<%-- <input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>--%>
<input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 导 入 "/>
<a href="${ctx}/airline/verify/import/template">下载模板</a>
</form>
......@@ -152,7 +152,7 @@
<div class="pagination">${page}</div>
<form style="display:none" id="form" action="dynamicFields.action?method=uploadFile" method="post"
enctype="multipart/form-data">
<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>
<%-- <input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>--%>
<input type="submit" value="确认提交">
</form>
......
......@@ -100,7 +100,7 @@
<div id="importBox" class="hide">
<form id="importForm" action="${ctx}/contact/airportBase/import" method="post" enctype="multipart/form-data"
class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');"><br/>
<input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>  
<%-- <input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>  --%>
<input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 导 入 "/>
<a href="${ctx}/contact/airportBase/template">下载模板</a>
</form>
......
......@@ -81,7 +81,7 @@
<div id="importBox" class="hide">
<form id="importForm" action="${ctx}/contact/airport/batchImport" method="post" enctype="multipart/form-data"
class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');"><br/>
<input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx'/><br/><br/>
<%-- <input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx'/><br/><br/>--%>
<input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 导 入 "/>
<a href="${ctx}/contact/airport/batchImport/template">下载模板</a>
</form>
......
......@@ -125,7 +125,7 @@
<div id="importBox" class="hide">
<form id="importForm" action="${ctx}/contact/contacts/batchImport" method="post" enctype="multipart/form-data"
class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');"><br/>
<input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>
<%-- <input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>--%>
<input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 导 入 "/>
<a href="${ctx}/contact/contacts/batchImport/template">下载模板</a>
</form>
......
......@@ -282,7 +282,7 @@
</div>
</form:form>
<form id="form" style="display:none" action="${ctx}/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>
<%--<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>--%>
<input type="submit" value="确认提交">
</form>
</body>
......
......@@ -5,23 +5,23 @@
<title>席位类型管理</title>
<meta name="decorator" content="default"/>
<script type="text/javascript">
$(document).ready(function() {
$("#no").focus();
myValidate();
$.get("${ctx}/contact/station/stationData", null, function(data) {
if (!!data) {
var html = "";
$("#stationId").html("<option value=''>--------- 请选择场站 ---------</option>");
for (var i = 0; i < data.length; i ++) {
html += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
}
var domParser = new DOMParser();
var doc = domParser.parseFromString(html, 'text/html');
$("#stationId").innerHTML(doc);
}
$("#stationId").select2().val('${seatTypeEntity.stationId}').trigger("change");
});
});
<%--$(document).ready(function() {--%>
<%-- $("#no").focus();--%>
<%-- myValidate();--%>
<%-- $.get("${ctx}/contact/station/stationData", null, function(data) {--%>
<%-- if (!!data) {--%>
<%-- var html = "";--%>
<%-- $("#stationId").html("<option value=''>--------- 请选择场站 ---------</option>");--%>
<%-- for (var i = 0; i < data.length; i ++) {--%>
<%-- html += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"--%>
<%-- }--%>
<%-- var domParser = new DOMParser();--%>
<%-- var doc = domParser.parseFromString(html, 'text/html');--%>
<%-- $("#stationId").innerHTML(doc);--%>
<%-- }--%>
<%-- $("#stationId").select2().val('${seatTypeEntity.stationId}').trigger("change");--%>
<%-- });--%>
<%--});--%>
function myValidate() {
$("#inputForm").validate({
......
......@@ -80,19 +80,19 @@
}
}
});
$.get("${ctx}/contact/airport/airportData", null, function(data) {
if (!!data) {
var html = "";
$("#airportIata").html("<option value=''>------- 请选择三字码 -------</option>");
for (var i = 0; i < data.length; i ++) {
html += "<option value='" + data[i].airportIata + "'>" + data[i].airportIata+"----"+ data[i].cityName + "</option>"
}
var domParser = new DOMParser();
var doc = domParser.parseFromString(html, 'text/html');
$("#airportIata").innerHTML(doc);
}
$("#airportIata").select2().val('${stationEntity.airportIata}').trigger("change");
});
<%--$.get("${ctx}/contact/airport/airportData", null, function(data) {--%>
<%-- if (!!data) {--%>
<%-- var html = "";--%>
<%-- $("#airportIata").html("<option value=''>------- 请选择三字码 -------</option>");--%>
<%-- for (var i = 0; i < data.length; i ++) {--%>
<%-- html += "<option value='" + data[i].airportIata + "'>" + data[i].airportIata+"----"+ data[i].cityName + "</option>"--%>
<%-- }--%>
<%-- var domParser = new DOMParser();--%>
<%-- var doc = domParser.parseFromString(html, 'text/html');--%>
<%-- $("#airportIata").innerHTML(doc);--%>
<%-- }--%>
<%-- $("#airportIata").select2().val('${stationEntity.airportIata}').trigger("change");--%>
<%--});--%>
});
</script>
</head>
......@@ -155,7 +155,7 @@
</div>
</form:form>
<form id="form" style="display:none" action="${ctx}/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>
<%--<input type="file" name="file" id="file" value="" accept=".xls,.xlsx"/><br/>--%>
<input type="submit" value="确认提交">
</form>
</body>
......
......@@ -20,44 +20,44 @@
}
$(function() {
$("#treeTable").treeTable({expandLevel : 2, column : 1}).show();
$.get("${ctx}/finnr/classify/delayCategoryData", null, function(data) {
/* console.log(data); */
if (!!data) {
var html = " ";
for (var i = 0; i < data.length; i ++) {
if(data[i].parentId==null){
html += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
}
}
var domParser = new DOMParser();
var doc = domParser.parseFromString(html, 'text/html');
$("#parent").innerHTML(doc);
$("#parent").val("${reParentId}").trigger("change");
}
});
});
<%--$(function() {--%>
<%-- $("#treeTable").treeTable({expandLevel : 2, column : 1}).show();--%>
<%-- $.get("${ctx}/finnr/classify/delayCategoryData", null, function(data) {--%>
<%-- /* console.log(data); */ --%>
<%-- if (!!data) {--%>
<%-- var html = " "; --%>
<%-- for (var i = 0; i < data.length; i ++) {--%>
<%-- if(data[i].parentId==null){--%>
<%-- html += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"--%>
<%-- }--%>
<%-- }--%>
<%-- var domParser = new DOMParser();--%>
<%-- var doc = domParser.parseFromString(html, 'text/html');--%>
<%-- $("#parent").innerHTML(doc);--%>
<%-- $("#parent").val("${reParentId}").trigger("change");--%>
<%-- }--%>
<%-- });--%>
<%-- });--%>
function displayChildrenId(pId) {
/* console.log(pId); */
$.get("${ctx}/finnr/classify/delayCategoryData", null, function(data) {
if (!!data) {
var html = " ";
$("#id").html("<option value=''>全部</option>");
for (var i = 0; i < data.length; i ++) {
if (data[i].parentId!=null&&data[i].parentId==pId) {
console.log(data[i].id);
html += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
}
}
var domParser = new DOMParser();
var doc = domParser.parseFromString(html, 'text/html');
$("#id").innerHTML(doc);
$("#id").val("${reId}").trigger("change");
}
});
<%--function displayChildrenId(pId) {--%>
<%-- /* console.log(pId); */--%>
<%-- $.get("${ctx}/finnr/classify/delayCategoryData", null, function(data) {--%>
<%-- if (!!data) {--%>
<%-- var html = " ";--%>
<%-- $("#id").html("<option value=''>全部</option>");--%>
<%-- for (var i = 0; i < data.length; i ++) {--%>
<%-- --%>
<%-- if (data[i].parentId!=null&&data[i].parentId==pId) { --%>
<%-- console.log(data[i].id); --%>
<%-- html += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"--%>
<%-- } --%>
<%-- }--%>
<%-- var domParser = new DOMParser();--%>
<%-- var doc = domParser.parseFromString(html, 'text/html');--%>
<%-- $("#id").innerHTML(doc);--%>
<%-- $("#id").val("${reId}").trigger("change");--%>
<%-- }--%>
<%-- });--%>
}
</script>
<style>
......
......@@ -24,20 +24,20 @@
});
/* 分类下拉框 */
$.get("${ctx}/finnr/delayRecord/delayCategoryData", null, function(data) {
if (!!data) {
var html = "";
for (var i = 0; i < data.length; i ++) {
if (data[i].pId!="0") {
html += "<option value='" + data[i].id + "'>" + data[i].name + " ---- " + data[i].pName +"</option>"
}
}
var domParser = new DOMParser();
var doc = domParser.parseFromString(html, 'text/html');
$("#categoryId").innerHTML(doc);
}
$("#categoryId").select2().val('${delayRecordEntity.categoryId}').trigger("change");
});
<%--$.get("${ctx}/finnr/delayRecord/delayCategoryData", null, function(data) {--%>
<%-- if (!!data) {--%>
<%-- var html = "";--%>
<%-- for (var i = 0; i < data.length; i ++) {--%>
<%-- if (data[i].pId!="0") {--%>
<%-- html += "<option value='" + data[i].id + "'>" + data[i].name + " ---- " + data[i].pName +"</option>"--%>
<%-- }--%>
<%-- }--%>
<%-- // var domParser = new DOMParser();--%>
<%-- // var doc = domParser.parseFromString(html, 'text/html');--%>
<%-- // $("#categoryId").innerHTML(doc);--%>
<%-- }--%>
<%-- $("#categoryId").select2().val('${delayRecordEntity.categoryId}').trigger("change");--%>
<%--});--%>
});
</script>
</head>
......
......@@ -40,7 +40,7 @@
<div id="importBox" class="hide">
<form id="importForm" action="${ctx}/sys/user/import" method="post" enctype="multipart/form-data"
class="form-search" style="padding-left:20px;text-align:center;" onsubmit="loading('正在导入,请稍等...');"><br/>
<input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>  
<%-- <input id="uploadFile" name="file" type="file" style="width:330px" accept=".xls,.xlsx"/><br/><br/>  --%>
<input id="btnImportSubmit" class="btn btn-primary" type="submit" value=" 导 入 "/>
<a href="${ctx}/sys/user/import/template">下载模板</a>
</form>
......
......@@ -58,7 +58,7 @@
<div class="control-group">
<label class="control-label">上传资料:</label>
<div class="controls">
<input type="file" name="file" id="file" value="" accept=".xls,.xlsx,.doc,.docx,.pdf"/><br/>
<%-- <input type="file" name="file" id="file" value="" accept=".xls,.xlsx,.doc,.docx,.pdf"/><br/>--%>
</div>
</div>
<div class="form-actions">
......
......@@ -30,7 +30,7 @@ public class ActionEnter {
this.rootPath = rootPath;
this.actionType = request.getParameter( "action" );
this.contextPath = request.getContextPath();
this.configManager = ConfigManager.getInstance( this.rootPath, this.contextPath, request.getRequestURI() );
// this.configManager = ConfigManager.getInstance( this.rootPath, this.contextPath, request.getRequestURI() );
}
......@@ -53,49 +53,49 @@ public class ActionEnter {
}
public String invoke() {
if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) {
return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString();
}
if ( this.configManager == null || !this.configManager.valid() ) {
return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString();
}
//
// if ( actionType == null || !ActionMap.mapping.containsKey( actionType ) ) {
// return new BaseState( false, AppInfo.INVALID_ACTION ).toJSONString();
// }
//
// if ( this.configManager == null || !this.configManager.valid() ) {
// return new BaseState( false, AppInfo.CONFIG_ERROR ).toJSONString();
// }
//
State state = null;
int actionCode = ActionMap.getType( this.actionType );
Map<String, Object> conf = null;
switch ( actionCode ) {
case ActionMap.CONFIG:
return this.configManager.getAllConfig().toString();
case ActionMap.UPLOAD_IMAGE:
case ActionMap.UPLOAD_SCRAWL:
case ActionMap.UPLOAD_VIDEO:
case ActionMap.UPLOAD_FILE:
conf = this.configManager.getConfig( actionCode );
state = new Uploader( request, conf ).doExec();
break;
case ActionMap.CATCH_IMAGE:
conf = configManager.getConfig( actionCode );
String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
state = new ImageHunter( conf ).capture( list );
break;
case ActionMap.LIST_IMAGE:
case ActionMap.LIST_FILE:
conf = configManager.getConfig( actionCode );
int start = this.getStartIndex();
state = new FileManager( conf ).listFile( start );
break;
}
//
// int actionCode = ActionMap.getType( this.actionType );
//
// Map<String, Object> conf = null;
//
// switch ( actionCode ) {
//
// case ActionMap.CONFIG:
// return this.configManager.getAllConfig().toString();
//
// case ActionMap.UPLOAD_IMAGE:
// case ActionMap.UPLOAD_SCRAWL:
// case ActionMap.UPLOAD_VIDEO:
// case ActionMap.UPLOAD_FILE:
// conf = this.configManager.getConfig( actionCode );
// state = new Uploader( request, conf ).doExec();
// break;
//
// case ActionMap.CATCH_IMAGE:
// conf = configManager.getConfig( actionCode );
// String[] list = this.request.getParameterValues( (String)conf.get( "fieldName" ) );
// state = new ImageHunter( conf ).capture( list );
// break;
//
// case ActionMap.LIST_IMAGE:
// case ActionMap.LIST_FILE:
// conf = configManager.getConfig( actionCode );
// int start = this.getStartIndex();
// state = new FileManager( conf ).listFile( start );
// break;
//
// }
//
return state.toJSONString();
}
......
......@@ -19,7 +19,7 @@ import java.util.Map;
public final class ConfigManager {
private final String rootPath;
private final String originalPath;
// private final String originalPath;
// private final String contextPath;
private static final String configFileName = "ueditor.json";
private String parentPath = null;
......@@ -38,12 +38,12 @@ public final class ConfigManager {
this.rootPath = rootPath;
// this.contextPath = contextPath;
if (contextPath.length() > 0) {
this.originalPath = this.rootPath + uri.substring(contextPath.length());
} else {
this.originalPath = this.rootPath + uri;
}
//
// if (contextPath.length() > 0) {
// this.originalPath = this.rootPath + uri.substring(contextPath.length());
// } else {
// this.originalPath = this.rootPath + uri;
// }
this.initEnv();
......@@ -59,11 +59,11 @@ public final class ConfigManager {
*/
public static ConfigManager getInstance(String rootPath, String contextPath, String uri) {
try {
return new ConfigManager(rootPath, contextPath, uri);
} catch (Exception e) {
// try {
// return new ConfigManager(rootPath, contextPath, uri);
// } catch (Exception e) {
return null;
}
// }
}
......@@ -148,30 +148,30 @@ public final class ConfigManager {
private void initEnv() throws FileNotFoundException, IOException {
// 文件验证
String path = this.originalPath;
path = FileManipulation.validateFile2(path);
File file = new File(FileManipulation.validateFile2(path));
if (!file.isAbsolute()) {
file = new File(file.getAbsolutePath());
}
this.parentPath = file.getParent();
try {
File cfg = new File(this.getConfigPath());
if (cfg.exists() && cfg.isFile()) {
String configContent = this.readFile(this.getConfigPath());
this.jsonConfig = new JSONObject(configContent);
} else {
URL in = ConfigManager.class.getClassLoader().getResource(ConfigManager.configFileName);
String configContent = this.readFile(in.getPath());
this.jsonConfig = new JSONObject(configContent);
}
} catch (Exception e) {
e.printStackTrace();
this.jsonConfig = null;
}
// String path = this.originalPath;
// path = FileManipulation.validateFile2(path);
// File file = new File(FileManipulation.validateFile2(path));
//
// if (!file.isAbsolute()) {
// file = new File(file.getAbsolutePath());
// }
//
// this.parentPath = file.getParent();
//
// try {
// File cfg = new File(this.getConfigPath());
// if (cfg.exists() && cfg.isFile()) {
// String configContent = this.readFile(this.getConfigPath());
// this.jsonConfig = new JSONObject(configContent);
// } else {
// URL in = ConfigManager.class.getClassLoader().getResource(ConfigManager.configFileName);
// String configContent = this.readFile(in.getPath());
// this.jsonConfig = new JSONObject(configContent);
// }
// } catch (Exception e) {
// e.printStackTrace();
// this.jsonConfig = null;
// }
}
......
......@@ -21,37 +21,37 @@ public class FileManager {
public FileManager(Map<String, Object> conf) {
this.rootPath = (String) conf.get("rootPath");
this.dir = this.rootPath + (String) conf.get("dir");
this.allowFiles = this.getAllowFiles(conf.get("allowFiles"));
this.count = (Integer) conf.get("count");
// this.rootPath = (String) conf.get("rootPath");
// this.dir = this.rootPath + (String) conf.get("dir");
// this.allowFiles = this.getAllowFiles(conf.get("allowFiles"));
// this.count = (Integer) conf.get("count");
}
public State listFile(int index) {
File dir = new File(this.dir);
// File dir = new File(this.dir);
State state = null;
if (!dir.exists()) {
return new BaseState(false, AppInfo.NOT_EXIST);
}
if (!dir.isDirectory()) {
return new BaseState(false, AppInfo.NOT_DIRECTORY);
}
Collection<File> list = FileUtils.listFiles(dir, this.allowFiles, true);
if (index < 0 || index > list.size()) {
state = new MultiState(true);
} else {
Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + this.count);
state = this.getState(fileList);
}
state.putInfo("start", index);
state.putInfo("total", list.size());
//
// if (!dir.exists()) {
// return new BaseState(false, AppInfo.NOT_EXIST);
// }
//
// if (!dir.isDirectory()) {
// return new BaseState(false, AppInfo.NOT_DIRECTORY);
// }
//
// Collection<File> list = FileUtils.listFiles(dir, this.allowFiles, true);
//
// if (index < 0 || index > list.size()) {
// state = new MultiState(true);
// } else {
// Object[] fileList = Arrays.copyOfRange(list.toArray(), index, index + this.count);
// state = this.getState(fileList);
// }
// state.putInfo("start", index);
// state.putInfo("total", list.size());
return state;
......
......@@ -45,16 +45,16 @@ public class BinaryUploader {
return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
}
ServletFileUpload upload = new ServletFileUpload(
new DiskFileItemFactory());
// ServletFileUpload upload = new ServletFileUpload(
// new DiskFileItemFactory());
if ( isAjaxUpload ) {
upload.setHeaderEncoding( "UTF-8" );
// upload.setHeaderEncoding( "UTF-8" );
}
try {
FileItemIterator iterator = upload.getItemIterator(request);
FileItemIterator iterator = null;
// iterator= upload.getItemIterator(request);
while (iterator.hasNext()) {
fileStream = iterator.next();
try {
......@@ -82,38 +82,38 @@ public class BinaryUploader {
return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
}
String savePath = (String) conf.get("savePath");
String originFileName = FileManipulation.validateFile(fileStream.getName());
// 文件安全验证
originFileName=FileManipulation.validateFile(originFileName);
String suffix = FileType.getSuffixByFilename(originFileName);
originFileName = originFileName.substring(0,
originFileName.length() - suffix.length());
savePath = savePath + suffix;
long maxSize = ((Long) conf.get("maxSize")).longValue();
if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
savePath = PathFormat.parse(savePath, originFileName);
String physicalPath = (String) conf.get("rootPath") + savePath;
InputStream is = fileStream.openStream();
State storageState = StorageManager.saveFileByInputStream(is,
physicalPath, maxSize);
is.close();
if (storageState.isSuccess()) {
storageState.putInfo("url", PathFormat.format(savePath));
storageState.putInfo("type", suffix);
storageState.putInfo("original", originFileName + suffix);
}
return storageState;
// String savePath = (String) conf.get("savePath");
// String originFileName = FileManipulation.validateFile(fileStream.getName());
// // 文件安全验证
// originFileName=FileManipulation.validateFile(originFileName);
// String suffix = FileType.getSuffixByFilename(originFileName);
//
// originFileName = originFileName.substring(0,
// originFileName.length() - suffix.length());
// savePath = savePath + suffix;
// long maxSize = ((Long) conf.get("maxSize")).longValue();
//
// if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
// return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
// }
//
// savePath = PathFormat.parse(savePath, originFileName);
//
// String physicalPath = (String) conf.get("rootPath") + savePath;
// InputStream is = fileStream.openStream();
// State storageState = StorageManager.saveFileByInputStream(is,
// physicalPath, maxSize);
// is.close();
//
// if (storageState.isSuccess()) {
// storageState.putInfo("url", PathFormat.format(savePath));
// storageState.putInfo("type", suffix);
// storageState.putInfo("original", originFileName + suffix);
// }
// return storageState;
} catch (FileUploadException e) {
return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
} catch (IOException e) {
......
......@@ -123,21 +123,21 @@ public class StorageManager {
private static State saveTmpFile(File tmpFile, String path) {
State state = null;
// 文件安全验证
path=FileManipulation.validateFile(path);
File targetFile = new File(path);
if (targetFile.canWrite()) {
return new BaseState(false, AppInfo.PERMISSION_DENIED);
}
try {
FileUtils.moveFile(tmpFile, targetFile);
} catch (IOException e) {
return new BaseState(false, AppInfo.IO_ERROR);
}
state = new BaseState(true);
state.putInfo( "size", targetFile.length() );
state.putInfo( "title", targetFile.getName() );
// path=FileManipulation.validateFile(path);
// File targetFile = new File(path);
// if (targetFile.canWrite()) {
// return new BaseState(false, AppInfo.PERMISSION_DENIED);
// }
// try {
// FileUtils.moveFile(tmpFile, targetFile);
// } catch (IOException e) {
// return new BaseState(false, AppInfo.IO_ERROR);
// }
//
// state = new BaseState(true);
// state.putInfo( "size", targetFile.length() );
// state.putInfo( "title", targetFile.getName() );
return state;
}
......
......@@ -207,79 +207,79 @@ public class GConstants {
return global;
}
private GConstants(){
// 加载基本配置文件
InputStream is = null;
ResourceLoader resourceLoader = null;
Resource resource = null;
for(String location:resources){// 加载配置文件
try {
resourceLoader = new DefaultResourceLoader();
resource = resourceLoader.getResource(location);
is = resource.getInputStream();
P.load(is);
LOG.debug("加载"+location+"成功");
} catch (Exception e) {
LOG.info("加载"+location+"失败", e);
} finally {
IOUtils.closeQuietly(is);
}
}
try {
Enumeration<?> enu = P.propertyNames();
while (enu.hasMoreElements()) {
try {
String key = (String) enu.nextElement();
String val = (String) P.get(key);
String decrypted = DES3Utils.decrypt(val, CONF_DESC_KEY);
if(decrypted != null){
P.put(key, decrypted);
}
} catch (Exception e) {
// TODO: handle exception
}
}
} catch (Exception e) {
// TODO: handle exception
}
try {
// 上传文件扩展名称限制
String extensions = GConstants.getValue("file.allow.extensions");
if(extensions != null && extensions.contains(SEMICOLON)){
if(extensions.length() != 0){
String[] patternList = extensions.split(SEMICOLON);
for (String ext : patternList) {
if(ext.trim().length() != 0){
FILE_FILTERS.put(ext.trim(), false);
}
}
}
}
// 图片后缀文件
extensions = GConstants.getValue("file.image.extensions");
if(extensions != null && extensions.contains(SEMICOLON)){
if(extensions.length() != 0){
String[] patternList = extensions.split(SEMICOLON);
for (String ext : patternList) {
if(ext.trim().length() != 0){
FILE_FILTERS.put(ext.trim(), true);
}
}
}
}
// 临时文件夹路径
if(P.getProperty("file.upload.dir") != null){
File tmp = new File(P.getProperty("file.upload.dir"), "tmp");
if(!tmp.exists())
tmp.mkdirs();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
// // 加载基本配置文件
// InputStream is = null;
// ResourceLoader resourceLoader = null;
// Resource resource = null;
// for(String location:resources){// 加载配置文件
// try {
// resourceLoader = new DefaultResourceLoader();
// resource = resourceLoader.getResource(location);
// is = resource.getInputStream();
// P.load(is);
//
// LOG.debug("加载"+location+"成功");
// } catch (Exception e) {
// LOG.info("加载"+location+"失败", e);
// } finally {
// IOUtils.closeQuietly(is);
// }
// }
// try {
//
// Enumeration<?> enu = P.propertyNames();
// while (enu.hasMoreElements()) {
// try {
// String key = (String) enu.nextElement();
// String val = (String) P.get(key);
//
// String decrypted = DES3Utils.decrypt(val, CONF_DESC_KEY);
// if(decrypted != null){
//
// P.put(key, decrypted);
// }
// } catch (Exception e) {
// // TODO: handle exception
// }
// }
// } catch (Exception e) {
// // TODO: handle exception
// }
// try {
// // 上传文件扩展名称限制
// String extensions = GConstants.getValue("file.allow.extensions");
// if(extensions != null && extensions.contains(SEMICOLON)){
// if(extensions.length() != 0){
// String[] patternList = extensions.split(SEMICOLON);
// for (String ext : patternList) {
// if(ext.trim().length() != 0){
// FILE_FILTERS.put(ext.trim(), false);
// }
// }
// }
// }
// // 图片后缀文件
// extensions = GConstants.getValue("file.image.extensions");
// if(extensions != null && extensions.contains(SEMICOLON)){
// if(extensions.length() != 0){
// String[] patternList = extensions.split(SEMICOLON);
// for (String ext : patternList) {
// if(ext.trim().length() != 0){
// FILE_FILTERS.put(ext.trim(), true);
// }
// }
// }
// }
// // 临时文件夹路径
// if(P.getProperty("file.upload.dir") != null){
// File tmp = new File(P.getProperty("file.upload.dir"), "tmp");
// if(!tmp.exists())
// tmp.mkdirs();
// }
// } catch (Exception e) {
// // TODO: handle exception
// e.printStackTrace();
// }
}
/**
......@@ -288,12 +288,12 @@ public class GConstants {
* @return
*/
public static String getValue(String key) {
if(key == null)
return null;
if (P.containsKey(key)) {
return P.getProperty(key);
}
return System.getProperty(key);
// if(key == null)
// return null;
// if (P.containsKey(key)) {
// return P.getProperty(key);
// }
return "";
}
public static String getValue(String key, String want) {
String val = getValue(key);
......
......@@ -67,47 +67,47 @@ public final class IPSeeker {
private static IPSeeker INS = new IPSeeker();
private IPSeeker() {
String dir = GConstants.getValue("geoip.db.dir");
try {
if(dir == null || dir.length() == 0){
dir = IPSeeker.class.getResource("/").getPath();
if (dir != null && dir.contains("WEB-INF")) {// 是WEB项目的时候获取WebContent下的路径
dir = dir.substring(0, dir.indexOf("WEB-INF"))+"res"+GConstants.FS;
} else {// 非WEB项目获取当前路径
File file = new File("");
dir = file.getAbsolutePath()+GConstants.FS+"res"+GConstants.FS;
}
}
File db = new File(dir+"QQWry.dat");
LOG.info("加载QQWry.dat数据:"+db.getAbsolutePath());
if(db.exists()){
this.ipFile = new RandomAccessFile(db, "r");
if (this.ipFile != null) {
this.ipBegin = readLong4(0L);
this.ipEnd = readLong4(4L);
if ((this.ipBegin == -1L) || (this.ipEnd == -1L)) {
this.ipFile.close();
this.ipFile = null;
}
}
LOG.info("成功加载QQWry.dat数据库");
}
} catch (Exception e) {
LOG.error("QQWry.dat数据库不可用");
e.printStackTrace();
}
try {
File db = new File(dir+"GeoLite2-City.mmdb");
LOG.info("加载GeoLite2-City.mmdb数据:"+db.getAbsolutePath());
if(db.exists()){
reader = new DatabaseReader.Builder(db).build();
LOG.info("成功加载GeoLite2-City.mmdb数据库");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error("GeoLite2-City.mmdb数据库不可用");
}
// String dir = GConstants.getValue("geoip.db.dir");
// try {
// if(dir == null || dir.length() == 0){
// dir = IPSeeker.class.getResource("/").getPath();
// if (dir != null && dir.contains("WEB-INF")) {// 是WEB项目的时候获取WebContent下的路径
// dir = dir.substring(0, dir.indexOf("WEB-INF"))+"res"+GConstants.FS;
// } else {// 非WEB项目获取当前路径
// File file = new File("");
// dir = file.getAbsolutePath()+GConstants.FS+"res"+GConstants.FS;
// }
// }
// File db = new File(dir+"QQWry.dat");
// LOG.info("加载QQWry.dat数据:"+db.getAbsolutePath());
// if(db.exists()){
// this.ipFile = new RandomAccessFile(db, "r");
// if (this.ipFile != null) {
// this.ipBegin = readLong4(0L);
// this.ipEnd = readLong4(4L);
// if ((this.ipBegin == -1L) || (this.ipEnd == -1L)) {
// this.ipFile.close();
// this.ipFile = null;
// }
// }
// LOG.info("成功加载QQWry.dat数据库");
// }
// } catch (Exception e) {
// LOG.error("QQWry.dat数据库不可用");
// e.printStackTrace();
// }
// try {
// File db = new File(dir+"GeoLite2-City.mmdb");
// LOG.info("加载GeoLite2-City.mmdb数据:"+db.getAbsolutePath());
// if(db.exists()){
// reader = new DatabaseReader.Builder(db).build();
// LOG.info("成功加载GeoLite2-City.mmdb数据库");
// }
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// LOG.error("GeoLite2-City.mmdb数据库不可用");
// }
}
public static IPSeeker getInstance() {
......
......@@ -34,21 +34,21 @@ public class UserfilesDownloadServlet extends HttpServlet {
String filepath = req.getRequestURI();
// 文件安全验证
filepath=FileManipulation.Manipulation(filepath);
int index = filepath.indexOf(GConstants.USERFILES_BASE_URL);
if(index >= 0) {
filepath = filepath.substring(index + GConstants.USERFILES_BASE_URL.length());
}
// int index = filepath.indexOf(GConstants.USERFILES_BASE_URL);
// if(index >= 0) {
// filepath = filepath.substring(index + GConstants.USERFILES_BASE_URL.length());
// }
try {
filepath = UriUtils.decode(filepath, "UTF-8");
} catch (UnsupportedEncodingException e1) {
logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);
}
File file = new File(GConstants.getUserfilesBaseDir() + GConstants.USERFILES_BASE_URL + filepath);
// File file = new File(GConstants.getUserfilesBaseDir() + GConstants.USERFILES_BASE_URL + filepath);
try {
FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
// FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
resp.setHeader("Content-Type", "application/octet-stream");
return;
} catch (FileNotFoundException e) {
} catch (Exception e) {
req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
}
......
......@@ -105,10 +105,10 @@ public class FileManipulation {
throw new LoadException("非法的文件请求,请不要上传或下载含有非法字符或后缀的文件 :" + filename);
}
}
filename = filename.replaceAll("\\.\\./", "");
filename = filename.replaceAll("\\.\\.\\\\", "");
filename = filename.replaceAll("\\.\\.", "");
return filename;
// filename = filename.replaceAll("\\.\\./", "");
// filename = filename.replaceAll("\\.\\.\\\\", "");
// filename = filename.replaceAll("\\.\\.", "");
return "";
}
public static void check(String filename) {
......
......@@ -43,39 +43,39 @@ public class CKFinderConnectorServlet extends ConnectorServlet {
final HttpServletResponse response, final boolean post) throws ServletException {
try {
Principal principal = (Principal) UserUtils.getPrincipal();
if (principal == null) {
return;
}
String command = request.getParameter("command");
String type = request.getParameter("type");
// 初始化时,如果startupPath文件夹不存在,则自动创建startupPath文件夹
if ("Init".equals(command)) {
// 当前文件夹可指定为模块名
String startupPath = request.getParameter("startupPath");
if (startupPath != null) {
String[] ss = startupPath.split(":");
if (ss.length == 2) {
String realPath = GConstants.getUserfilesBaseDir() + "/" + ss[0] + ss[1];
realPath = FileManipulation.validateFile(realPath);
File fileRealPath = new File(FileManipulation.validateFile(realPath));
if (fileRealPath.exists() == false) {
fileRealPath.mkdirs();
}
}
}
// 快捷上传,自动创建当前文件夹,并上传到该路径
} else if ("QuickUpload".equals(command) && type != null) {
// 当前文件夹可指定为模块名
String currentFolder = request.getParameter("currentFolder");
String realPath = GConstants.getUserfilesBaseDir() + "/" + type + (currentFolder != null ? currentFolder : "");
// 验证文件安全
realPath = FileManipulation.validateFile(realPath);
File fileRealPath = new File(FileManipulation.validateFile(realPath));
if (fileRealPath.exists() == false) {
fileRealPath.mkdirs();
}
}
// Principal principal = (Principal) UserUtils.getPrincipal();
// if (principal == null) {
// return;
// }
// String command = request.getParameter("command");
// String type = request.getParameter("type");
// // 初始化时,如果startupPath文件夹不存在,则自动创建startupPath文件夹
// if ("Init".equals(command)) {
// // 当前文件夹可指定为模块名
// String startupPath = request.getParameter("startupPath");
// if (startupPath != null) {
// String[] ss = startupPath.split(":");
// if (ss.length == 2) {
// String realPath = GConstants.getUserfilesBaseDir() + "/" + ss[0] + ss[1];
// realPath = FileManipulation.validateFile(realPath);
// File fileRealPath = new File(FileManipulation.validateFile(realPath));
// if (fileRealPath.exists() == false) {
// fileRealPath.mkdirs();
// }
// }
// }
// // 快捷上传,自动创建当前文件夹,并上传到该路径
// } else if ("QuickUpload".equals(command) && type != null) {
// // 当前文件夹可指定为模块名
// String currentFolder = request.getParameter("currentFolder");
// String realPath = GConstants.getUserfilesBaseDir() + "/" + type + (currentFolder != null ? currentFolder : "");
// // 验证文件安全
// realPath = FileManipulation.validateFile(realPath);
// File fileRealPath = new File(FileManipulation.validateFile(realPath));
// if (fileRealPath.exists() == false) {
// fileRealPath.mkdirs();
// }
// }
} catch (Exception e) {
// TODO: handle exception
}
......
......@@ -70,72 +70,72 @@ public class SailingFileService extends CrudService<SailingFileDao, SailingFileE
String moduleName, String verifId) {
FileManipulation.check(originalFilename);
SailingFileEntity sailingFile = new SailingFileEntity();
OutputStream os = null;
ByteArrayOutputStream baos = null;
String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
// OutputStream os = null;
// ByteArrayOutputStream baos = null;
// String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
try {
// // 文件扩展名称不能为NULL
// if (StringUtils.isBlank(originalFilename)) {
// return null;
// }
// String extesionName = Util.getExtensionName(originalFilename);
// 文件扩展名称不能为NULL
if (StringUtils.isBlank(originalFilename)) {
return null;
}
String extesionName = Util.getExtensionName(originalFilename);
// 文件扩展名称不能为NULL
if (extesionName == null || extesionName.length() == 0) {
return null;
}
in = new BufferedInputStream(in);
baos = new ByteArrayOutputStream();
byte[] buf = new byte[GConstants.BUFFER_SIZE];
// 以写字节的方式写文件
int size = in.read(buf);
while (size != -1) {
baos.write(buf, 0, size);
size = in.read(buf);
}
byte[] data = baos.toByteArray();
// if (extesionName == null || extesionName.length() == 0) {
// return null;
// }
// in = new BufferedInputStream(in);
// baos = new ByteArrayOutputStream();
// byte[] buf = new byte[GConstants.BUFFER_SIZE];
// // 以写字节的方式写文件
// int size = in.read(buf);
// while (size != -1) {
// baos.write(buf, 0, size);
// size = in.read(buf);
// }
// byte[] data = baos.toByteArray();
// 待扩展名称的MOD5
String md5 = DigestUtils.md5Hex(data) + extesionName;
sailingFile.setFileName(originalFilename);
sailingFile.setFileSize(Integer.toString(data.length));
sailingFile.setMd5(md5);
sailingFile.setExtesion(extesionName);
sailingFile.setVerifId(verifId);
// 如果没有传则默认保存到files下面
if (StringUtils.isBlank(moduleName)) {
moduleName = "files";
} else {
// 替换非法字符串
moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");
moduleName = moduleName.replaceAll("[\\|//]+", "/");
// 如果没有传则默认保存到files下面
if (moduleName.length() == 0 || moduleName.length() > 64) {
moduleName = "files";
}
}
// String md5 = DigestUtils.md5Hex(data) + extesionName;
//
// sailingFile.setFileName(originalFilename);
//
// sailingFile.setFileSize(Integer.toString(data.length));
// sailingFile.setMd5(md5);
// sailingFile.setExtesion(extesionName);
// sailingFile.setVerifId(verifId);
// // 如果没有传则默认保存到files下面
// if (StringUtils.isBlank(moduleName)) {
// moduleName = "files";
// } else {
// // 替换非法字符串
// moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");
// moduleName = moduleName.replaceAll("[\\|//]+", "/");
// // 如果没有传则默认保存到files下面
// if (moduleName.length() == 0 || moduleName.length() > 64) {
// moduleName = "files";
// }
// }
// 文件保存路径:基本路径+模块名称+日期
String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
String basePath = moduleName + GConstants.FS + extesionName.replaceAll("\\.", "") + GConstants.FS;
// 上传文件基本地址
File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath);
// 验证文件安全
FileManipulation.validateFile(baseUploadDir.getPath());
if (!baseUploadDir.exists()) {
baseUploadDir.mkdirs();
}
sailingFile.setFilePath(baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5);
// 文件保存地址
File uploadFilePath = new File(baseUploadDir, md5);
// 验证文件安全
FileManipulation.validateFile(uploadFilePath.getPath());
// 将数据保存到指定文件
os = new FileOutputStream(uploadFilePath);
os = new BufferedOutputStream(os);
os.write(data);
os.flush();
// String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
// String basePath = moduleName + GConstants.FS + extesionName.replaceAll("\\.", "") + GConstants.FS;
// // 上传文件基本地址
// File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath);
// // 验证文件安全
// FileManipulation.validateFile(baseUploadDir.getPath());
// if (!baseUploadDir.exists()) {
// baseUploadDir.mkdirs();
// }
// sailingFile.setFilePath(baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5);
// // 文件保存地址
// File uploadFilePath = new File(baseUploadDir, md5);
// // 验证文件安全
// FileManipulation.validateFile(uploadFilePath.getPath());
// // 将数据保存到指定文件
// os = new FileOutputStream(uploadFilePath);
// os = new BufferedOutputStream(os);
// os.write(data);
// os.flush();
} catch (Exception e) {
} finally {
IOUtils.closeQuietly(os);
......
......@@ -66,20 +66,20 @@ public class SailingFileController extends BaseController {
@RequiresPermissions("vrf:sailingfile:edit")
@RequestMapping(value = "/upload", method=RequestMethod.POST)
public String upload(HttpServletRequest request, MultipartFile file, RedirectAttributes redirectAttributes){
String id=request.getParameter("id");
// String id=request.getParameter("id");
String fileName = file.getOriginalFilename();
// String fileName = file.getOriginalFilename();
// 文件安全验证
fileName= FileManipulation.validateFile(fileName);
// fileName= FileManipulation.validateFile(fileName);
try {
InputStream in=file.getInputStream();
String moduleName = "airline";
String sessionId = DigestUtils.md5Hex(Util.getRandom(100, 999)+":"
+System.currentTimeMillis()+":"+Util.getRandom(100, 999));
SailingFileEntity sailingFileEntity= sailingFileService.addUploadFile(sessionId, in, "",fileName, moduleName,id);
sailingFileService.delete(sailingFileEntity);
sailingFileService.save(sailingFileEntity);
addMessage(redirectAttributes, "保存成功");
// InputStream in=file.getInputStream();
// String moduleName = "airline";
// String sessionId = DigestUtils.md5Hex(Util.getRandom(100, 999)+":"
// +System.currentTimeMillis()+":"+Util.getRandom(100, 999));
// SailingFileEntity sailingFileEntity= sailingFileService.addUploadFile(sessionId, in, "",fileName, moduleName,id);
// sailingFileService.delete(sailingFileEntity);
// sailingFileService.save(sailingFileEntity);
// addMessage(redirectAttributes, "保存成功");
return "redirect:" + adminPath + "/airline/verify/list?repage";
} catch (Exception e) {
addMessage(redirectAttributes, "上传失败"+e.getMessage());
......@@ -92,42 +92,42 @@ public class SailingFileController extends BaseController {
@RequiresPermissions("vrf:sailingfile:edit")
@RequestMapping(value = "/download", method=RequestMethod.GET)
public String download(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes){
String verifId=request.getParameter("verifId");
SailingFileEntity sailingFileEntity= sailingFileService.get(verifId);
//获得请求文件名
String filename = sailingFileEntity.getFileName();
InputStream in = null;
OutputStream out = null;
try {
String downloadFileName=new String( filename.getBytes("gbk"),"ISO8859-1");
//设置文件MIME类型
response.setContentType(request.getServletContext().getMimeType(filename));
//设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+downloadFileName);
//读取目标文件,通过response将目标文件写到客户端
//获取目标文件的绝对路径
String fullFileName = GConstants.FILE_UPLOAD_DIR+sailingFileEntity.getFilePath();
//System.out.println(fullFileName);
// 文件安全验证
fullFileName= FileManipulation.validateFile(fullFileName);
//读取文件
in = new FileInputStream(FileManipulation.validateFile(fullFileName));
out = response.getOutputStream();
//写文件
int b;
while((b=in.read())!= -1)
{
out.write(b);
}
} catch (Exception e) {
// TODO: handle exception
} finally{
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
// String verifId=request.getParameter("verifId");
// SailingFileEntity sailingFileEntity= sailingFileService.get(verifId);
// //获得请求文件名
// String filename = sailingFileEntity.getFileName();
//
// InputStream in = null;
// OutputStream out = null;
// try {
//
// String downloadFileName=new String( filename.getBytes("gbk"),"ISO8859-1");
// //设置文件MIME类型
// response.setContentType(request.getServletContext().getMimeType(filename));
// //设置Content-Disposition
// response.setHeader("Content-Disposition", "attachment;filename="+downloadFileName);
// //读取目标文件,通过response将目标文件写到客户端
// //获取目标文件的绝对路径
// String fullFileName = GConstants.FILE_UPLOAD_DIR+sailingFileEntity.getFilePath();
// //System.out.println(fullFileName);
// // 文件安全验证
// fullFileName= FileManipulation.validateFile(fullFileName);
// //读取文件
// in = new FileInputStream(FileManipulation.validateFile(fullFileName));
// out = response.getOutputStream();
//
// //写文件
// int b;
// while((b=in.read())!= -1)
// {
// out.write(b);
// }
// } catch (Exception e) {
// // TODO: handle exception
// } finally{
// IOUtils.closeQuietly(in);
// IOUtils.closeQuietly(out);
// }
return null;
}
......
......@@ -17,8 +17,8 @@ import java.io.*;
@Service
@Transactional(readOnly = true)
public class FileService {
private static Logger LOG = Logger.getLogger(FileService.class);
private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
// private static Logger LOG = Logger.getLogger(FileService.class);
// private static final String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
public String upload(MultipartFile multipartFile, String originalFilename) {
......@@ -27,42 +27,43 @@ public class FileService {
ByteArrayOutputStream baos = null;
try {
String extesionName = Util.getExtensionName(originalFilename);
InputStream in = multipartFile.getInputStream();
in = new BufferedInputStream(in);
baos = new ByteArrayOutputStream();
byte[] buf = new byte[GConstants.BUFFER_SIZE];
// 以写字节的方式写文件
int size = in.read(buf);
while (size != -1) {
baos.write(buf, 0, size);
size = in.read(buf);
}
byte[] data = baos.toByteArray();
// 待扩展名称的MOD5
String md5 = DigestUtils.md5Hex(data) + extesionName;
// 文件扩展名称不能为NULL
if (extesionName == null || extesionName.length() == 0) {
LOG.debug("无法获取文件扩展名:" + originalFilename);
}
// String extesionName = Util.getExtensionName(originalFilename);
// InputStream in = multipartFile.getInputStream();
// in = new BufferedInputStream(in);
// baos = new ByteArrayOutputStream();
// byte[] buf = new byte[GConstants.BUFFER_SIZE];
// // 以写字节的方式写文件
// int size = in.read(buf);
// while (size != -1) {
// baos.write(buf, 0, size);
// size = in.read(buf);
// }
// byte[] data = baos.toByteArray();
// // 待扩展名称的MOD5
// String md5 = DigestUtils.md5Hex(data) + extesionName;
// // 文件扩展名称不能为NULL
// if (extesionName == null || extesionName.length() == 0) {
// LOG.debug("无法获取文件扩展名:" + originalFilename);
// }
// 文件保存路径:基本路径+模块名称+日期
String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
String basePath = moduleName + GConstants.FS + extesionName.replaceAll("\\.", "") + GConstants.FS;
// String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);
// String basePath = moduleName + GConstants.FS + extesionName.replaceAll("\\.", "") + GConstants.FS;
// 上传文件基本地址
File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath);
if (!baseUploadDir.exists()) {
baseUploadDir.mkdirs();
}
// File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath);
// if (!baseUploadDir.exists()) {
// baseUploadDir.mkdirs();
// }
// 文件保存地址
File uploadFilePath = new File(baseUploadDir, md5);
LOG.info("原文件服务器绝对路径:" + uploadFilePath);
// 将数据保存到指定文件
os = new FileOutputStream(uploadFilePath);
os = new BufferedOutputStream(os);
os.write(data);
os.flush();
return baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath + md5;
} catch (IOException ex) {
// File uploadFilePath = new File(baseUploadDir, md5);
// LOG.info("原文件服务器绝对路径:" + uploadFilePath);
// // 将数据保存到指定文件
// os = new FileOutputStream(uploadFilePath);
// os = new BufferedOutputStream(os);
// os.write(data);
// os.flush();
// return baseDatePath + GConstants.FS + GConstants.FILE_IMAGE_ACTUALS + GConstants.FS + basePath + md5;
return "";
} catch (Exception ex) {
return "error" + ex.getMessage();
}
......
......@@ -32,42 +32,42 @@ public class FileUploadController extends BaseController {
public void SaveImg(HttpServletRequest request, MultipartFile file, HttpServletResponse response){
try {
request.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "text/html");
// 转换为文件类型的request
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> fileIterator = multipartRequest.getFileNames();
// 获取对应file对象
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
String fileKey = fileIterator.next();
// 获取对应文件
MultipartFile multipartFile = fileMap.get(fileKey);
String fileName= multipartFile.getOriginalFilename();
// 文件安全验证
FileManipulation.validateFile(fileName);
String url=fileService.upload(multipartFile,fileName);
JSONObject js=new JSONObject();
js.put("message","success");
js.put("url",url);
response.getWriter().write(js.toString());
// request.setCharacterEncoding("utf-8");
// response.setHeader("Content-Type", "text/html");
//F
// // 转换为文件类型的request
// MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// Iterator<String> fileIterator = multipartRequest.getFileNames();
// // 获取对应file对象
// Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
// String fileKey = fileIterator.next();
// // 获取对应文件
// MultipartFile multipartFile = fileMap.get(fileKey);
// String fileName= multipartFile.getOriginalFilename();
//
// // 文件安全验证
// FileManipulation.validateFile(fileName);
//
// String url=fileService.upload(multipartFile,fileName);
// JSONObject js=new JSONObject();
//
// js.put("message","success");
// js.put("url",url);
// response.getWriter().write(js.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
@RequestMapping(value = "/upload", method=RequestMethod.POST)
public void upload(HttpServletRequest request, MultipartFile file, RedirectAttributes redirectAttributes, HttpServletResponse response) throws IOException{
String fileName= file.getOriginalFilename();
// 文件安全验证
FileManipulation.validateFile(fileName);
String url=fileService.upload(file,fileName);
JSONObject js=new JSONObject();
js.put("message","success");
js.put("url",url);
response.getWriter().write(js.toString());
// String fileName= file.getOriginalFilename();
// // 文件安全验证
// FileManipulation.validateFile(fileName);
// String url=fileService.upload(file,fileName);
// JSONObject js=new JSONObject();
//
// js.put("message","success");
// js.put("url",url);
// response.getWriter().write(js.toString());
}
}
......@@ -71,72 +71,72 @@ public class DocumentService extends CrudService<DocumentDao, DocumentEntity> {
String moduleName,DocumentEntity documentEntity){
OutputStream os = null;
ByteArrayOutputStream baos = null;
String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
// String PATH_FORMAt = GConstants.getValue("file.path.format", "{yyyy}{mm}{dd}");
try {
if(StringUtils.isBlank(originalFilename)){// 文件扩展名称不能为NULL
return null;
}
String extesionName = Util.getExtensionName(originalFilename);
if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL
return null;
}
in = new BufferedInputStream(in);
baos = new ByteArrayOutputStream();
byte[] buf = new byte[GConstants.BUFFER_SIZE];
// 以写字节的方式写文件
int size = in.read(buf);
while (size != -1) {
baos.write(buf, 0, size);
size = in.read(buf);
}
byte[] data = baos.toByteArray();
// byte[] data = IOUtils.toByteArray(in);
// 待扩展名称的MOD5
String md5 = DigestUtils.md5Hex(data)+extesionName;
String filesize="";
documentEntity.setFileName(originalFilename);
double d=data.length/1024;
if(d>1023){
d=d/1024;
DecimalFormat df =new DecimalFormat("#.00");
filesize=df.format(d)+"MB";
}else{
DecimalFormat df =new DecimalFormat("#0.0");
filesize=df.format(d)+"KB";
}
documentEntity.setFileSize(filesize );
documentEntity.setMd5(md5);
documentEntity.setExtesion(extesionName);
if(StringUtils.isBlank(moduleName)){// 如果没有传则默认保存到files下面
moduleName = "files";
} else{
moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串
moduleName = moduleName.replaceAll("[\\|//]+", "/");
if(moduleName.length() == 0 || moduleName.length()>64)// 如果没有传则默认保存到files下面
moduleName = "files";
}
// 文件保存路径:基本路径+模块名称+日期
String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);//FORMAT.format(System.currentTimeMillis());
String basePath = moduleName+GConstants.FS+extesionName.replaceAll("\\.", "")+GConstants.FS;
// 上传文件基本地址
File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath);
// 验证文件安全
FileManipulation.validateFile(baseUploadDir.getPath());
if(!baseUploadDir.exists()){// 如果文件夹不存在则创建
baseUploadDir.mkdirs();
}
documentEntity.setFilePath(baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5);
// 文件保存地址
File uploadFilePath = new File(baseUploadDir, md5);
// 验证文件安全
FileManipulation.validateFile(uploadFilePath.getPath());
// 将数据保存到指定文件
os = new FileOutputStream(uploadFilePath);
os = new BufferedOutputStream(os);
os.write(data);
os.flush();
// if(StringUtils.isBlank(originalFilename)){// 文件扩展名称不能为NULL
// return null;
// }
// String extesionName = Util.getExtensionName(originalFilename);
// if(extesionName == null || extesionName.length() == 0){// 文件扩展名称不能为NULL
// return null;
// }
// in = new BufferedInputStream(in);
// baos = new ByteArrayOutputStream();
// byte[] buf = new byte[GConstants.BUFFER_SIZE];
// // 以写字节的方式写文件
// int size = in.read(buf);
// while (size != -1) {
// baos.write(buf, 0, size);
// size = in.read(buf);
// }
// byte[] data = baos.toByteArray();
//
//// byte[] data = IOUtils.toByteArray(in);
// // 待扩展名称的MOD5
// String md5 = DigestUtils.md5Hex(data)+extesionName;
// String filesize="";
// documentEntity.setFileName(originalFilename);
// double d=data.length/1024;
// if(d>1023){
// d=d/1024;
// DecimalFormat df =new DecimalFormat("#.00");
// filesize=df.format(d)+"MB";
// }else{
// DecimalFormat df =new DecimalFormat("#0.0");
// filesize=df.format(d)+"KB";
// }
// documentEntity.setFileSize(filesize );
// documentEntity.setMd5(md5);
// documentEntity.setExtesion(extesionName);
// if(StringUtils.isBlank(moduleName)){// 如果没有传则默认保存到files下面
// moduleName = "files";
// } else{
// moduleName = moduleName.replaceAll("^/+|/+$|[^0-9|a-z|A-Z|/]+", "");// 替换非法字符串
// moduleName = moduleName.replaceAll("[\\|//]+", "/");
// if(moduleName.length() == 0 || moduleName.length()>64)// 如果没有传则默认保存到files下面
// moduleName = "files";
// }
// // 文件保存路径:基本路径+模块名称+日期
// String baseDatePath = PathFormatUtils.parse(PATH_FORMAt);//FORMAT.format(System.currentTimeMillis());
// String basePath = moduleName+GConstants.FS+extesionName.replaceAll("\\.", "")+GConstants.FS;
// // 上传文件基本地址
// File baseUploadDir = new File(GConstants.FILE_UPLOAD_DIR, baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath);
// // 验证文件安全
// FileManipulation.validateFile(baseUploadDir.getPath());
// if(!baseUploadDir.exists()){// 如果文件夹不存在则创建
// baseUploadDir.mkdirs();
// }
// documentEntity.setFilePath(baseDatePath+GConstants.FS+GConstants.FILE_IMAGE_ACTUALS+GConstants.FS+basePath+md5);
//
// // 文件保存地址
// File uploadFilePath = new File(baseUploadDir, md5);
// // 验证文件安全
// FileManipulation.validateFile(uploadFilePath.getPath());
// // 将数据保存到指定文件
// os = new FileOutputStream(uploadFilePath);
// os = new BufferedOutputStream(os);
// os.write(data);
// os.flush();
} catch (Exception e) {
// TODO: handle exception
} finally {
......
......@@ -73,21 +73,21 @@ public class DocumentController extends BaseController {
@RequiresPermissions("vrf:document:edit")
@RequestMapping(value = "save")
public String save(DocumentEntity documentEntity, MultipartFile file, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
if (!beanValidator(model, documentEntity)){
return form(documentEntity, model);
}
if(file.getSize()==0){
addMessage(redirectAttributes, "保存失败,请上传文件后再进行保存");
return "redirect:" + adminPath + "/verify/document/list?repage";
}
FileManipulation.check(file.getOriginalFilename());
String fileName = file.getOriginalFilename();
// if (!beanValidator(model, documentEntity)){
// return form(documentEntity, model);
// }
// if(file.getSize()==0){
// addMessage(redirectAttributes, "保存失败,请上传文件后再进行保存");
// return "redirect:" + adminPath + "/verify/document/list?repage";
// }
// FileManipulation.check(file.getOriginalFilename());
// String fileName = file.getOriginalFilename();
try {
InputStream in=file.getInputStream();
String moduleName = "verify";
String sessionId = DigestUtils.md5Hex(Util.getRandom(100, 999)+":"
+System.currentTimeMillis()+":"+Util.getRandom(100, 999));
documentEntity= documentService.addUploadFile(sessionId, in, "",fileName, moduleName,documentEntity);
// InputStream in=file.getInputStream();
// String moduleName = "verify";
// String sessionId = DigestUtils.md5Hex(Util.getRandom(100, 999)+":"
// +System.currentTimeMillis()+":"+Util.getRandom(100, 999));
// documentEntity= documentService.addUploadFile(sessionId, in, "",fileName, moduleName,documentEntity);
} catch (Exception e) {
// TODO: handle exception
......@@ -109,43 +109,43 @@ public class DocumentController extends BaseController {
@RequiresPermissions("vrf:sailingfile:edit")
@RequestMapping(value = "/download", method=RequestMethod.GET)
public String download(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes){
String id=request.getParameter("id");
DocumentEntity documentEntity= documentService.get(id);
//获得请求文件名
String filename = documentEntity.getFileName();
InputStream in = null;
OutputStream out = null;
try {
//设置文件MIME类型
response.setContentType(request.getServletContext().getMimeType(filename));
String downloadFileName=new String( filename.getBytes("gbk"),"ISO8859-1");
//设置Content-Disposition
response.setHeader("Content-Disposition", "attachment;filename="+downloadFileName);
//读取目标文件,通过response将目标文件写到客户端
//获取目标文件的绝对路径
String fullFileName = GConstants.FILE_UPLOAD_DIR+documentEntity.getFilePath();
//System.out.println(fullFileName);
// 验证文件安全
fullFileName= FileManipulation.validateFile(fullFileName);
//读取文件 并验证文件安全
in = new FileInputStream(FileManipulation.validateFile(fullFileName));
out = response.getOutputStream();
//写文件
int b;
while((b=in.read())!= -1)
{
out.write(b);
}
} catch (Exception e) {
// TODO: handle exception
} finally{
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
// String id=request.getParameter("id");
// DocumentEntity documentEntity= documentService.get(id);
// //获得请求文件名
// String filename = documentEntity.getFileName();
// InputStream in = null;
// OutputStream out = null;
// try {
//
//
// //设置文件MIME类型
// response.setContentType(request.getServletContext().getMimeType(filename));
// String downloadFileName=new String( filename.getBytes("gbk"),"ISO8859-1");
// //设置Content-Disposition
// response.setHeader("Content-Disposition", "attachment;filename="+downloadFileName);
// //读取目标文件,通过response将目标文件写到客户端
// //获取目标文件的绝对路径
// String fullFileName = GConstants.FILE_UPLOAD_DIR+documentEntity.getFilePath();
// //System.out.println(fullFileName);
// // 验证文件安全
// fullFileName= FileManipulation.validateFile(fullFileName);
// //读取文件 并验证文件安全
// in = new FileInputStream(FileManipulation.validateFile(fullFileName));
// out = response.getOutputStream();
//
// //写文件
// int b;
// while((b=in.read())!= -1)
// {
// out.write(b);
// }
// } catch (Exception e) {
// // TODO: handle exception
// } finally{
// IOUtils.closeQuietly(in);
// IOUtils.closeQuietly(out);
// }
//
return null;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment