上传
<style type="text/css">
/*文件上传 控件*/
.upload{position:relative; display:inline-block; height:33px;line-height:33px; overflow:hidden;vertical-align:middle; cursor:pointer;}
.upload .upload-input-file{position:absolute; right:0; top:0; font-size:100px; opacity:0; filter:alpha(opacity=0);cursor:pointer;}
.upload .upload-btn{outline:none;border:0; padding:0px 15px;color:#fff;background:#1D92AF;cursor:pointer; /*border-radius:3px;*/}
.upload .upload-url { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; border-radius:2px;
border: solid 1px #ddd; width: 200px; height:30px;-webkit-line-height: 1;line-height: 30px\9;-ms-line-height: 30px; text-indent:3px;}
.upload .upload-tip {display:none; background-color:#1c84c6; padding:2px 10px; color:#fefefe; font-size:12px !important;border-radius:3px;}
</style>
//上传
{
field: "",
title: '<@spring.message "sys.config.upload_file"/>',
headerAttributes: {style: "text-align:center;"},
attributes: {style: "white-space:nowrap;text-overflow:ellipsis;text-align:center;"},
width: 120,
template:function (dataItem) {
var salesActivitiesId = dataItem.salesActivitiesId;
var formId = 'myForm'+salesActivitiesId;
var fileId = 'file'+salesActivitiesId;
if (ifNotNull(salesActivitiesId)){
return '<form id="'+formId+'" action="" enctype="multipart/form-data" style="border-radius:8px;width: 40px;height: 20px;;">\n' +
' <div style="float:left;">\n' +
' <span class="upload" >\n' +
' <span class="btn btn-primary" style="float:left;" >\n' +
' <i class="fa fa-file-excel-o" style="margin-right:3px;"></i><@spring.message "sys.config.upload_file"/>\n' +
' </span>\n' +
' <span class="upload-tip"></span>\n' +
' <input accept=""\n' +
' type="file" id="file" name="file" onchange="myUploadFile('+salesActivitiesId+')" class="upload-input-file" />\n' +
' </span>\n' +
' </div>\n' +
' </form>';
}else {
return '';
}
},
},
//文件上传
function myUploadFile(salesActivitiesId) {
//form表单的id
var formId = '#myForm'+salesActivitiesId;
//file的id
var fileId = '#file'+salesActivitiesId;
//获取数据
var formData = new FormData($(formId)[0]);
if ($(fileId).val() === ''){//这个判断是解决IE浏览器的问题
return;
}
$.ajax({
url: '${base.contextPath}/hawk/sales/activities/myUploadFile?salesActivitiesId='+salesActivitiesId,
type: 'POST',
data: formData,
async : false,
cache : false,
contentType : false,
processData : false,
success:function (data) {
if(data.success){
//将返回的数据显示在grid中
// $('#grid').data("kendoGrid").dataSource.data(data.rows);
//grid.dataSource.data(data.rows);
//数据来源是Excel
// viewModel.isExcelData = true;
kendo.ui.showInfoDialog({
message: '上传成功'
});
$('#gridDetail').data("kendoGrid").dataSource.page(1);//这个就直接进行查询
}else {
kendo.ui.showInfoDialog({
message: data.message
});
}
}
})
$(fileId).val("");
}
控制层
@RequestMapping("/hawk/sales/activities/myUploadFile")
public ResponseData myUploadFile(String salesActivitiesId, SalesActivities dto, HttpServletRequest request, HttpServletResponse response){
/**
*
* 功能描述: 文件上传
*
* @param: [request, response]
* @return: com.hand.hap.system.dto.ResponseData
* @auther: leizhe
* @date: 2019/3/20 17:23
*/
ResponseData responseData = service.myUploadFile(salesActivitiesId,request,response,createRequestContext(request));
return responseData;
}
实现层
@Override
public ResponseData myUploadFile(String salesActivitiesId, HttpServletRequest request, HttpServletResponse response, IRequest requestContext) {
/**
*
* 功能描述: 文件上传
*
* @param: [salesActivitiesId, request, response, requestContext]
* @return: com.hand.hap.system.dto.ResponseData
* @auther: leizhe
* @date: 2019/3/21 10:21
*
*/
ResponseData responseData = new ResponseData();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
//获取文件并将文件上传到指定目录下
FileItem item = (FileItem)items.get(0);
String name = item.getName();
//文件名
String fileNameAndPath = "E:\\" + name + "---" + UUID.randomUUID();
//校验文件名称
if (name.indexOf("---") != -1){
responseData.setSuccess(false);
responseData.setMessage("文件名中不能出现‘---’字符串");
return responseData;
}
//首先查看文件是否已经存在
SalesActivities salesActivities = new SalesActivities();
salesActivities.setSalesActivitiesId(Long.parseLong(salesActivitiesId));
List<SalesActivities> query = salesActivitiesMapper.select(salesActivities);
String currentFileName = query.get(0).getCurrentFileName();
if (currentFileName != null){
responseData.setSuccess(false);
responseData.setMessage("文件已经上传");
return responseData;
}
//根据文件名和salesActivitiesId,更新hawk_sales_activities
salesActivitiesMapper.updateCurrentFilePath(salesActivitiesId,fileNameAndPath);
//获取io流
InputStream inputStream = item.getInputStream();
//输出文件
FileOutputStream fos = new FileOutputStream(fileNameAndPath);
byte datas[] = new byte[1024*8];
int len = 0;
while((len = inputStream.read(datas))!=-1){
fos.write(datas,0,len);
}
//关闭IO流
inputStream.close();
fos.close();
responseData.setSuccess(true);
} catch (Exception e) {
e.printStackTrace();
responseData.setSuccess(false);
responseData.setMessage("error");
}
return responseData;
}
下载
//下载
{
field: "",
title: '<@spring.message "hap.download"/>',
headerAttributes: {style: "text-align:center;"},
attributes: {style: "white-space:nowrap;text-overflow:ellipsis;text-align:center;"},
width: 120,
template:function (dataItem) {
console.info(dataItem);
var thisresult = JSON.stringify(dataItem).replace(/"/g, '"');
var currentFileName = dataItem.currentFileName;
if (ifNotNull(currentFileName)){
return '<span id="TEMPLATEEXPORT" class="btn btn-primary k-grid-excel" style="float:left;margin-right:5px;" onclick="myDownLoadFile('+thisresult+')">\n' +
' <i class="fa fa-file-excel-o" style="margin-right:3px;"></i><@spring.message "hap.download"/>\n' +
'</span>';
}else {
return '';
}
},
},
对应div
<div id="batchDiv" style="display: none"></div>
//文件下载
function myDownLoadFile(thisresult) {
var currentFileName = thisresult.currentFileName;
if (!ifNotNull(currentFileName)){
kendo.ui.showInfoDialog({
message: '还未上传文件'
});
return;
}
//token
var $inputToken=$('<input>').attr({name:"${_csrf.parameterName}",value:"${_csrf.token}",type:"hidden"});
//文件名称
var currentFileName =$('<input>').attr({name:"currentFileName",value:thisresult.currentFileName,type:"hidden"});
var $form = $("<form>");
$form.attr({
target: '_self',
method: 'post',
action: '${base.contextPath}/hawk/sales/activities/myDownLoadFile'
});
$form.append($inputToken);
$form.append(currentFileName);
$form.id='smbForm';
$("#batchDiv").empty().append($form);
$($form).submit();
$("#batchDiv").empty();
}
控制层
@RequestMapping("/hawk/sales/activities/myDownLoadFile")
public ResponseData myDownLoadFile(String currentFileName, SalesActivities dto, HttpServletRequest request, HttpServletResponse response){
/**
*
* 功能描述: 文件上传
*
* @param: [request, response]
* @return: com.hand.hap.system.dto.ResponseData
* @auther: leizhe
* @date: 2019/3/20 17:23
*/
return service.myDownLoadFile(dto,request,response);
}
实现层
@Override
public ResponseData myDownLoadFile(SalesActivities dto, HttpServletRequest request, HttpServletResponse response) {
//获取服务器中的文件
String currentFileName = dto.getCurrentFileName();
//获取文件名称
String fileNameAndPath = currentFileName.split("---")[0];
int i = fileNameAndPath.lastIndexOf("\\");
String fileName = fileNameAndPath.substring(i+1);
//开始下载文件
response.reset();
response.setContentType("application/octet-stream" + ";charsets=" + "UTF-8");
try {
response.addHeader("Content-Disposition", "attachment; filename=\"" + "" + new String(fileName.getBytes("GBK"),"ISO8859-1") + "\"");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
BufferedInputStream inputStream = null;
BufferedOutputStream out = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(currentFileName));
out = new BufferedOutputStream(response.getOutputStream());
IOUtils.copy(inputStream, out);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(out);
}
return null;
}