如何上传CSV文件,然后自动将数据插入数据库?

ygya80vv  于 2022-10-23  发布在  Spring
关注(0)|答案(4)|浏览(171)

我有一个基于Java的Spring MVC应用程序,它也使用了Spring安全性。我正在使用Hibernate作为这个Web应用程序的ORM工具。
以下是我的要求--
用户将能够使用Web浏览器上传CSV文件。CSV文件的格式已知具有以下5个字段:

userId, location, itemId, quantity, tranDate
001, NY, 00A8D5, 2, 12/31/2012
002, MN, 00A7C1, 10, 12/22/2012
.
.

像这样大约有100排。
我在项目中使用Super CSV:

private void readWithCsvBeanReader(String CSV_FILENAME) throws Exception {

    String CSV_FILENAME = "\\\\Serv01\\Files\\QueryResult.csv";
    //String CSV_FILENAME = "C:\\Files\\QueryResult.csv";
    ICsvBeanReader beanReader = null;
    try {
        beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME),
                CsvPreference.STANDARD_PREFERENCE);

        // the header elements are used to map the values to the bean (names
        // must match)
        final String[] header = beanReader.getHeader(true);
        // get Cell Processor
        final CellProcessor[] processors = getProcessors();

在这里,我正在读取CSV文件的内容,然后使用Hibernate插入它。
这可以很好地工作,因为我在本地或Windows共享上提供CSV路径。

String CSV_FILENAME = "\\\\Serv01\\Files\\QueryResult.csv";
or via this:
String CSV_FILENAME = "C:\\Files\\QueryResult.csv";

1.如何使用Spring MVC在网页上通过按钮提供CSV文件的路径位置?
1.是否也可以从远程位置自动提取文件,以便我将文件上传到一个ftp位置,然后程序可以连接到远程ftp位置并按计划处理该文件?
PS:我是文件操作的新手,如果有人能指出一些文章,那就太好了。

anauzrmj

anauzrmj1#

像这样大约有100排。
不要费心将CSV保存为临时文件,因为SpringMulitpart将为您做这件事,只需直接插入行(处理请求可能需要更长的时间,但考虑到您表面上的当前知识,您可以担心以后如何优化)

private void readWithCsvBeanReader(MultipartFile uploadedFile) throws Exception {

    ICsvBeanReader beanReader = null;
    try {
        beanReader = new CsvBeanReader(new InputStreamReader(uploadedFile.getInputStream()),
                CsvPreference.STANDARD_PREFERENCE);

        // the header elements are used to map the values to the bean (names
        // must match)
        final String[] header = beanReader.getHeader(true);
        // get Cell Processor
        final CellProcessor[] processors = getProcessors();

让您的控制器如下所示:

@RequestMapping(value = "/add", method=RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file) throws IOException {
// call your csv parsing code.
}

确保您的表单看起来类似于:

<h1>Add a File for testing</h1>
<form method="post" action="/add" class="well form-vertical" enctype="multipart/form-data">
    <input type="file" name="file" />
    <button type="submit" class="btn">{{actionLabel}}</button>
</form>

注意enctype

对于输入和输出,您应该了解Java's IO Decorator pattern

我建议你尽量简单,这样你就可以学习基础知识了。然后再考虑添加更强大的解决方案/库。

w8ntj3qf

w8ntj3qf2#

您需要创建一个FileUploadController,如here所述。然后,当您在Servlet中将文件作为流获得时,您需要执行所有验证并将文件保存到临时/永久位置,以便稍后在DB导入过程中使用它。

4dbbbstv

4dbbbstv3#

为了使用远程的FTP文件位置,我将研究一下Spring集成。有关这方面的文档是here

bvn4nwqk

bvn4nwqk4#

你可以试着用这个

final String[] header = beanReader.getHeader(true);

相关问题