angularjs 控制上传下载,先下载模板,然后填写内容,然后再提交,后台是ssh
1,页面按钮
<button class="btn btn-danger btn-o" type="button" ng-click="downloadTemplate()">模板下载</button>
<button class="btn btn-danger btn-o" ><input class="input-upload" type="file" value = '上传文件' nv-file-select="" uploader=uploaderExcel ></input>上传文件</button>
2,js方法 自定义只能让他上传excel文件
//模板下载
$scope.downloadTemplate=function(){
$("#exportForm").attr("action",basepath+"/a/buy/supplyApply/downloadTemplate.do");
$("#exportForm").submit();
}
//模板上传
/* $scope.downloadTemplate=function(){
$("#exportForm").attr("action",basepath+"/a/buy/supplyApply/downloadTemplate.do");
$("#exportForm").submit();
}*/
// app.controller('UploadCtrl', [ '$scope', '$http','SweetAlert', 'FileUploader','$rootScope', function($scope, $http, SweetAlert, FileUploader,$rootScope) {
$scope.files=[];
$scope.uploadType="1";
$scope.isPicture=true;
//上传控制器,必需
var uploadurl = basepath+'/a/buy/supplyApply/upload.do';
var uploaderExcel = $scope.uploaderExcel = new FileUploader({
url: uploadurl,
autoUpload:true
});
//自定义过滤器
uploaderExcel.filters.push({
name: 'customFilter',
fn: function (item/*{File|FileLikeObject}*/, options) {
return this.queue.length < 10;
}
});
uploaderExcel.onWhenAddingFileFailed = function (item, filter, options) {
};
uploaderExcel.onAfterAddingFile = function (fileItem) {
};
uploaderExcel.onAfterAddingAll = function (addedFileItems) {
// console.info('onAfterAddingAll', addedFileItems);
// console.info(addedFileItems.length);
/* for(var i = 0; i < addedFileItems.length; i++){
var fileItem = addedFileItems[i];
// console.info(fileItem);
if((fileItem.file.type).indexOf("image/")==-1){
SweetAlert.swal("提示", "请上传图片!", "warning");
$scope.isPicture = false;
$scope.uploader.clearQueue();
return ;
}else{
$scope.isPicture = true;
}
};*/
};
uploaderExcel.onSuccessItem = function (fileItem, response, status, headers) {
// console.info(fileItem);
// console.info(response);
// console.info(status);
// console.info(headers);
};
uploaderExcel.onCompleteItem = function (fileItem, response, status, headers) {
toaster.pop("info", "", response.message);
if(response.success){
console.info(response.data);
$scope.p.line = response.data;
}
};
uploaderExcel.onCompleteAll = function () {
};
// }]);
3,后台代码
//自定义模板类
public class SupplyApplyLineTemplate {
private String materialCode;//物资编号
private Double quantity;//数量
private String remarks;
//导出
@ExcelField(title = "物资编号", align = 2, sort = 1)
public String getMaterialCodeExcel() {
return null==materialCode?"":quantity.toString();
}
@ExcelField(title = "数量", align = 2, sort = 2)
public String getQuantityExcel() {
return null==quantity?"0":quantity.toString();
}
@ExcelField(title = "备注", align = 2, sort = 3)
public String getRemarks() {
return remarks;
}
}
// 这个导出下载excel方法是封装了得基于注解导出excel
@RequiresPermissions("buy:supplyApply:view")
@RequestMapping(value = "downloadTemplate")
@ResponseBody
public ResultData downloadTemplate( HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
try {
String fileName = "甲供申请物资明细.xlsx";
ExportExcel excel=new ExportExcel("甲供申请明细数据", SupplyApplyLineTemplate.class);
excel.setDictService(dictService);
List<SupplyApplyLineTemplate> list = new ArrayList<>();
excel.setDataList(list).write(response, fileName).dispose();
return null;
} catch (Exception e) {
return new ResultData(false, "导出用户失败!失败信息:" + e.getMessage());
}
}
@ResponseBody
@RequestMapping(value = "/upload")
public ResultData upload(MultipartFile file, HttpServletRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("upload() - 开始");
}
ResultData result = readData(file, request);
if (logger.isDebugEnabled()) {
logger.debug("upload() - 结束");
}
return result;
}
//正则判断是否为数字
public static boolean isNumber(String str){
String reg = "^[0-9]+(.[0-9]+)?$";
return str.matches(reg);
}
public ResultData readData(MultipartFile file, HttpServletRequest request){
ResultData result = new ResultData();
result.setSuccess(true);
if (null == file || file.isEmpty()) {
result.setMessage("文件未上传");
return result;
}
// 项目的真实路径
String baseDir = request.getServletContext().getRealPath("/");
String filePath = null;
File saveFile = null;
try {
//相对路径
filePath = Global.getBaseDir() + DateUtils.getYear() + "/" + DateUtils.getMonth() + "/"
+ new Random().nextLong() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
// 保存上传的文件
saveFile = new File(baseDir, filePath);
FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
ImportExcel ei = new ImportExcel(baseDir+filePath, 1); //读取数据
List<SupplyApplyLineVo> list = new ArrayList<>();
List<String> materials = new ArrayList<String>();
for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) { //行
Row row = ei.getRow(i);
SupplyApplyLineVo vo = new SupplyApplyLineVo();
for (int j = 0; j < ei.getLastCellNum(); j++) { //列
Object val = ei.getCellValue(row, j);
switch (j) {
case 0: //第一列 物料编号
if(StringUtils.isNotEmpty(val.toString())){
if(!materials.contains(val.toString())){
materials.add(val.toString());
MaterialsMasterDataVo materialsMasterData =new MaterialsMasterDataVo();
materialsMasterData.setMaterialCode(val.toString());
Page<MaterialsMasterDataVo> page = materialsMasterDataService.find(new Page<MaterialsMasterData>(), materialsMasterData);
if(page.getList() != null && page.getList().size()>0){
vo.setMaterial(page.getList().get(0));
}else{
result.setSuccess(false);
result.setMessage("数据异常:第" + (i-1) +"行物料不存在!请核实");
return result;
}
}else{
result.setSuccess(false);
result.setMessage("数据异常:第" + (i-1) +"行物料已存在,请合并!");
return result;
}
}else{
result.setSuccess(false);
result.setMessage("数据异常:第" +(i-1) +"行物料未填写!请核实");
return result;
}
break;
case 1: //数量
if(StringUtils.isNotEmpty(val.toString()) && isNumber(val.toString())){
vo.setQuantity(Double.valueOf(df.format(Double.valueOf(val.toString()))));
}else{
result.setSuccess(false);
result.setMessage("数据异常:第" + (i-1) +"行数量为空或不为数字!");
return result;
}
break;
case 2: //备注
if(StringUtils.isNotEmpty(val.toString()))
vo.setRemarks(val.toString());
break;
default:
break;
}
}
list.add(vo);
}
result.setData(list);
// 保存附件表
} catch (Exception e) {
logger.error("数据读取异常", e);
result.setSuccess(false);
result.setMessage("数据读取异常:" + e.getMessage());
return result;
} finally { //清除上传excel文件
if(saveFile.isFile() && saveFile.exists()){
saveFile.delete();
}
}
result.setSuccess(true);
result.setMessage("数据读取成功");
return result;
}