4

我有基于 Java 的 Spring MVC 应用程序,它也使用 Spring 安全性。我正在使用 hibernate 作为这个 web 应用程序的 ORM 工具。

以下是我的要求——

用户将能够使用 Web 浏览器上传 CSV 文件。CSV 文件的格式已知有以下 5 个字段:

userId, location, itemId, 数量, tranDate
001,纽约,00A8D5,2,2012 年 12 月 31 日
002,明尼苏达州,00A7C1,10,2012 年 12 月 22 日
.
.

像这样有大约 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 文件路径位置?

  2. 是否也可以从远程位置自动获取文件,以便我将文件上传到 FTP 位置,然后程序可以连接到远程 ftp 位置并按计划处理文件?

PS:我是文件操作的新手,如果有人可以指出一些文章,那就太好了。

4

3 回答 3

6

像这样有大约 100 行。

不要费心将 CSV 保存为 tmp 文件,因为 Spring 的Mulitpart会为您执行此操作并直接插入行(该请求可能需要更长的时间来处理,但鉴于您表面上的当前知识,您可以担心稍后优化

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.
}

确保你的 FORM 看起来像:

<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 的 IO 装饰器模式

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

于 2013-01-01T16:53:23.903 回答
0

您需要按照此处的说明创建 FileUploadController 。然后,当您将文件作为 servlet 中的流获取时,您需要进行所有验证并将文件保存到临时/永久位置,以便以后在数据库导入过程中使用它。

于 2013-01-01T07:48:11.693 回答
0

为了使用远程 FTP 文件位置,我会研究 Spring Integration。这方面的文档在这里

于 2013-01-01T16:07:30.517 回答