java—如何将html表单与文件输入绑定,并将SpringRestController绑定到后端(无js)

kd3sttzy  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(252)

我有springrestcontroller,带有自动连接的jparepository和h2嵌入式数据库。

@RestController
    public class BooksController {

        @Autowired
        private BookRepository repository;

// POST method will be here
}

ui是一个简单的表单 <input type="file"> 标签

<form class="form-horizontal" method="POST" action="/book/upload" enctype="multipart/form-data">
    <div class="form-group">
        <label for="fileInput">Specify path to XLS file:</label>
        <input type="file" name="file" id="fileInput"
               accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
        <input type="submit" class="btn btn-primary" value="Upload">
    </div>
</form>

我需要一个方法,我可以从输入表格处理文件。如何将ui输入窗体与restcontroller绑定?是否有专门的libs用于在后端处理xls文件?
主要目标是解析xls文件并将数据存储在db中。

5kgi1eie

5kgi1eie1#

解决方案是使用multipartfile作为requestparam,在restcontroller的方法中使用multipart\ form\ data\ value。

@RequestMapping(value = "/book/upload",
        method = RequestMethod.POST,
        consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public String upload(@RequestParam(value = "file") MultipartFile file) throws IOException {

    HashMap<String, List<String>> data = ReadExcelUtil.readData(file);
    StringBuilder response = new StringBuilder();
    data.forEach((String key, List<String> value) -> {
        response.append("Data for ").append(key).append(" column:\n");
        value.forEach((String val) -> response.append(val).append("\n"));
    });
    return response.toString();
}

为了处理xls文件,实现了readexcelutil。它包含readdata方法,该方法返回hashmap,其中键-值构成第一行(标题),值-当前列的数据列表。

public class ReadExcelUtil {

    public static HashMap<String, List<String>> readData(MultipartFile file) {

        HashMap<String, List<String>> result = new HashMap<>();
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Workbook workbook = null;
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        switch (extension.toLowerCase()) {
            case "xls": {
                try {
                    workbook = new HSSFWorkbook(inputStream);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                break;
            }
            case "xlsx": {
                try {
                    workbook = new XSSFWorkbook(inputStream);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                break;
            }
            default:
                throw new RuntimeException("Unsupported file extension. Valid are XLS and XLSX.");
        }

        Sheet sheet = workbook.getSheetAt(0);
        for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) {
            final int cellIndex = i;
            final List<String> value = new ArrayList<>();
            final String[] key = {""};
            sheet.forEach((Row row) -> {
                row.forEach((Cell cell) -> {
                    final int rowIndex = row.getRowNum();
                    if (cellIndex == cell.getColumnIndex()) {
                        if (rowIndex == 0) {
                            key[0] = getCellValue(cell);
                        } else {
                            value.add(getCellValue(cell));
                        }
                    }
                });
                result.put(key[0], value);
            });
        }
        return result;
    }

    protected static String getCellValue(Cell cell) {

        String result = "";
        if (cell != null) {
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_BOOLEAN:
                    result = String.valueOf(cell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    result = String.valueOf(cell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    result = cell.getStringCellValue();
                    break;
                case Cell.CELL_TYPE_BLANK:
                    break;
                case Cell.CELL_TYPE_ERROR:
                    break;
            }
        }
        return result;
    }
}

相关问题