AngularJS上传、下载文件

上传

先给出样式图:
在这里插入图片描述
HTML如下:

<div>
	<form method="post" enctype="multipart/form-data">
		<input type="file" id = "uploadFile" name="uploadFile"><br/>
	    <button style="" type="button" ng-click="batchUploadUser()">上传
	    </button>
	</form>
</div>

JS方法如下:

$scope.batchUploadUser = function () {
    const form = new FormData();
    const file = document.getElementById("uploadFile").files[0];
    if (file == null) {
        new hullabaloo().send("添加失败", "请选择文件", "danger");
    }
    form.append('file', file);
    $http({
        method: 'POST',
        url: '/commons/batchAddUser.do',
        data: form,
        headers: {'Content-Type': undefined},
        transformRequest: angular.identity
    }).success(function (response) {
        if (response.status === '1') {
            new hullabaloo().send("添加成功", "", "success");
        } else {
            new hullabaloo().send("添加失败", response.msg, "danger");
        }
    }).error(function (response) {
        new hullabaloo().send("添加失败", response.msg, "danger");
    });
	// reset
    document.getElementById("uploadFile").value = '';
}

对应的后端接口:

@RequestMapping(value = "/batchAddUser", method = RequestMethod.POST)
public ServiceStatus batchAddUser(@RequestParam(value = "file") MultipartFile uploadFile, HttpSession session) throws Exception {
    if (uploadFile == null) {
        return new ServiceStatus(Status.Fail, "请选择文件");
    }
    if (uploadFile.getSize() > 0) {
        String path = session.getServletContext().getRealPath("");
        String fileName = uploadFile.getOriginalFilename();
        if (fileName.endsWith(ExcelUtil.XLS) || fileName.endsWith(ExcelUtil.XLSX)) {
            File file = new File(path, fileName);
            uploadFile.transferTo(file);
            List<UploadUser> userList = excelUtil.readExcel(file.getCanonicalPath());
            return this.batchInsert(userList);
        }
    }
    return new ServiceStatus(Status.Fail, "文件为空或者格式不对");
}
@Component
public class ExcelUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);

    public static final String XLS = "xls";
    public static final String XLSX = "xlsx";

    public List<UploadUser> readExcel(String fileName) {
        Workbook workbook = null;
        FileInputStream inputStream = null;
        try {
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            File excelFile = new File(fileName);
            if (!excelFile.exists()) {
                LOGGER.warn("Excel file not exist!");
                return null;
            }
            inputStream = new FileInputStream(excelFile);
            workbook = this.getWorkbook(inputStream, fileType);
            return this.parseExcel(workbook);
        } catch (Exception e) {
            LOGGER.warn("readExcel failed, filename: " + fileName + " error: " + e.getMessage());
            return null;
        } finally {
            try {
                if (null != workbook) {
                    workbook.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                LOGGER.warn("关闭数据流出错!错误信息:" + e.getMessage());
            }
        }
    }

    /**
     * 根据文件后缀名类型获取对应的工作簿对象
     *
     * @param inputStream 读取文件的输入流
     * @param fileType    文件后缀名类型(xls或xlsx)
     * @return 包含文件数据的工作簿对象
     */
    private Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
        Workbook workbook = null;
        if (fileType.equalsIgnoreCase(XLS)) {
            workbook = new HSSFWorkbook(inputStream);
        } else if (fileType.equalsIgnoreCase(XLSX)) {
            workbook = new XSSFWorkbook(inputStream);
        }
        return workbook;
    }

    /**
     * 解析Excel数据
     *
     * @param workbook Excel工作簿对象
     * @return 解析结果
     */
    private List<UploadUser> parseExcel(Workbook workbook) {
        List<UploadUser> resultDataList = new ArrayList<>();
        for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            Sheet sheet = workbook.getSheetAt(sheetNum);
            if (sheet == null) {
                continue;
            }
            int firstRowNum = sheet.getFirstRowNum();
            Row firstRow = sheet.getRow(firstRowNum);
            if (null == firstRow) {
                LOGGER.warn("parseExcel failed no data in first row!");
            }
            int rowStart = firstRowNum + 1;
            int rowEnd = sheet.getPhysicalNumberOfRows();
            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (null == row) {
                    continue;
                }
                UploadUser resultData = convertRowToData(row);
                resultDataList.add(resultData);
            }
        }
        return resultDataList;
    }

    /**
     * 提取每一行中需要的数据,构造成为一个结果数据对象
     * <p>
     * 当该行中有单元格的数据为空或不合法时,忽略该行的数据
     *
     * @param row 行数据
     * @return 解析后的行数据对象,行数据错误时返回null
     */
    private UploadUser convertRowToData(Row row) {
        UploadUser user = new UploadUser();
        int cellNum = 0;
        Cell cell = row.getCell(cellNum++);
        String username = this.convertCellValueToString(cell);
        user.setUsername(username);

        cell = row.getCell(cellNum++);
        String domainName = this.convertCellValueToString(cell);
        user.setDomainName(domainName);

        cell = row.getCell(cellNum++);
        String mail = this.convertCellValueToString(cell);
        user.setMail(mail);

        cell = row.getCell(cellNum++);
        String department = this.convertCellValueToString(cell);
        user.setDepartment(department);

        cell = row.getCell(cellNum++);
        String role = this.convertCellValueToString(cell);
        user.setRole(Integer.parseInt(role));

        return user;
    }

    /**
     * 将单元格内容转换为字符串
     */
    private String convertCellValueToString(Cell cell) {
        if (cell == null) {
            return null;
        }
        String returnValue = null;
        switch (cell.getCellType()) {
            case NUMERIC:
                Double doubleValue = cell.getNumericCellValue();
                DecimalFormat df = new DecimalFormat("0");
                returnValue = df.format(doubleValue);
                break;
            case STRING:
                returnValue = cell.getStringCellValue();
                break;
            case BOOLEAN:
                boolean booleanValue = cell.getBooleanCellValue();
                returnValue = Boolean.toString(booleanValue);
                break;
            case FORMULA:
                returnValue = cell.getCellFormula();
                break;
            default:
                break;
        }
        return returnValue;
    }
}

JS上传并解析填充表单

上面的上传是常规的文件上传方式,有两个input标签,分别用于选择文件和
在这里插入图片描述

<a href="javascript:" class="file">导入
	<input type="file" name="file" ng-click="chooseFile(1)" ng-disabled="groupInputWay"
          id="uploadGroupFile"/>
</a>

<style>
	.file {
	  width: 30px;
	  height: 32px;
	  /* 必须保留 */
	  position: relative;
	  display: inline-block;
	  padding-top: 3px;
	  text-decoration: underline;
	  border: 0;
	  cursor: pointer;
	  border-radius: 2px;
	  text-align: center;
	  line-height: 30px;
	  font-family: PingFangSC-Medium;
	}
	
	.file input {
	  width: 30px;
	  height: 32px;
	  position: absolute;
	  font-size: 0;
	  cursor: pointer;
	  right: 0;
	  top: 0;
	  opacity: 0;
	}
</style>
let times1 = 0;
$scope.chooseFile = function (fieldType) {
    if (fieldType === 1 && times1 === 0) {
        document.getElementById("uploadGroupFile").addEventListener("change", () => {
            // 必须写在listen里面
            $scope.uploadFile(fieldType);
        });
        times1++;
    }
};

const excelSuffix = ['xlsx', 'xls'];
// 上传文件
$scope.uploadFile = function (fieldType) {
    let file;
    if (fieldType === 1) {
        file = document.getElementById("uploadGroupFile").files[0];
        $scope.uploadFileWay1 = true;
    }
    if (file === undefined) {
        new hullabaloo().send("导入失败", "请选择文件", "danger");
    }
    if (excelSuffix.includes(file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase())) {
        if (typeof (FileReader) != "undefined") {
            const reader = new FileReader();
            // For Browsers other than IE.
            if (reader.readAsBinaryString) {
                reader.onload = function (e) {
                    $scope.processExcel(e.target.result, fieldType);
                };
                reader.readAsBinaryString(file);
            } else {
                // For IE Browser.
                reader.onload = function (e) {
                    let data = "";
                    const bytes = new Uint8Array(e.target.result);
                    for (let i = 0; i < bytes.byteLength; i++) {
                        data += String.fromCharCode(bytes[i]);
                    }
                    $scope.processExcel(data, fieldType);
                };
                reader.readAsArrayBuffer(file);
            }
        } else {
            $scope.clearFileUpload(fieldType);
            new hullabaloo().send("导入失败", "当前浏览器不支持H5", "danger");
        }
    } else {
        $scope.clearFileUpload(fieldType);
        new hullabaloo().send("导入失败", "请上传Excel文件", "danger");
    }
    if (fieldType === 1) {
        document.getElementById("uploadGroupFile").value = '';
    } else if (fieldType === 2) {
        document.getElementById("uploadZxUserFile").value = '';
    } else if (fieldType === 3) {
        document.getElementById("uploadZjUserFile").value = '';
    }
};

// Excel解析
$scope.processExcel = function (data, fieldType) {
    // Read the Excel File data.
    const workbook = XLSX.read(data, {
        type: 'binary'
    });
    // Fetch the name of First Sheet.
    const firstSheet = workbook.SheetNames[0];
    // Read all rows from First Sheet into an JSON array.
    const excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);
    // Display the data from Excel file in Table.
    $scope.$apply(function () {
        const result = $scope.parseRow(excelRows, fieldType);
        if (result.includes(undefined)) {
            $scope.clearFileUpload(fieldType);
            new hullabaloo().send("导入失败", "导入数据有误,请对照示例检查", "danger");
            // 防止脏数据填充
            return;
        }
        if (fieldType === 1) {
            // 组别自动填充
            $scope.group_filter2 = $scope.buildGroupName(result);
        } else if (fieldType === 2) {
            // 坐席
            $scope.selectZxUserList = $scope.buildZxUser(result);
        } else if (fieldType === 3) {
            // 质检员
            $scope.selowerlist2 = $scope.buildZjUser(result);
        }
    });
};

// groupName填充
$scope.buildGroupName = function (array) {
    const result = [];
    for (let i = 0; i < array.length; i++) {
        result.push({"groupName": array[i]})
    }
    return result;
};

// ZxUser填充
$scope.buildZxUser = function (array) {
    const result = [];
    for (let i = 0; i < array.length; i++) {
        result.push({"realName": array[i]})
    }
    return result;
};

// 质检员填充
$scope.buildZjUser = function (array) {
    const result = [];
    for (let i = 0; i < array.length; i++) {
        result.push({"userName": array[i]})
    }
    return result;
};

// 获取数据
$scope.parseRow = function (rows, fieldType) {
    const result = [];
    for (let i = 0; i < rows.length; i++) {
        if (fieldType === 1) {
            result.push(rows[i].组别);
        } else if (fieldType === 2) {
            result.push(rows[i].坐席);
        } else if (fieldType === 3) {
            result.push(rows[i].质检员);
        }
    }
    return result;
};

// 清空
$scope.clearFileUpload = function (fieldType) {
    if (fieldType === 1) {
        document.getElementById("uploadGroupFile").value = '';
        $scope.uploadFileWay1 = false;
        $scope.group_filter2 = [];
    } else if (fieldType === 2) {
        document.getElementById("uploadZxUserFile").value = '';
        $scope.uploadFileWay2 = false;
        $scope.selectZxUserList = [];
    } else if (fieldType === 3) {
        document.getElementById("uploadZjUserFile").value = '';
        $scope.uploadFileWay3 = false;
        $scope.selowerlist2 = [];
    }
};

下载

参考

Angular JS 上传文件

posted @ 2020-11-18 15:38  johnny233  阅读(14)  评论(0编辑  收藏  举报  来源