在Spring Boot中上传时读取CSV文件

时间:2018-12-04 13:05:09

标签: java spring csv spring-boot

我在 spring boot 中有用于上传文件的代码。已经成功上传并将文件放在文件夹中。我已经从批处理服务运行中获得了代码。但是我仍然对从上传数据中读取数据CSV感到困惑。

我要修改。当我上传文件“特别是csv”时,系统将以CSV文件格式显示数据。

您能帮我吗,上传时如何从CSV中获取数据?

控制器

package com.mkyong.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class UploadController {

    //Save the uploaded file to this folder
    private static String UPLOADED_FOLDER = "D:\\spring\\video\\";

    @GetMapping("/")
    public String index() {
        return "upload";
    }

    @PostMapping("/upload") // //new annotation since 4.3
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }

        try {

            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "uploadStatus";
    }

}

模型

package com.mkyong.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="article")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name="title")
    private String title;

    @Column(name="category")
    private String category;

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getCategory() {
        return category;
    }
    public void setCategory(String category) {
        this.category = category;
    }


}

查看

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>

<h1>Spring Boot file upload example</h1>

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>
</body>
</html>

在youtube和教程网站中搜索了我,但找不到该方法。

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

byte[] bytes = file.getBytes();
ByteArrayInputStream inputFilestream = new ByteArrayInputStream(bytes);
BufferedReader br = new BufferedReader(new InputStreamReader(inputFilestream ));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();

答案 1 :(得分:0)

1.模型类 = Listing.java

  1. 资源 .csv 文件位于 resources/static/listing.csv
private void createListingFromCsvRecord() {
      
            String path = "classpath:static/listings.csv";
            ResultSet rs = new Csv().read(path, null, null);
            List<Listing> list = new ArrayList<>();
            while (rs.next()) {
                Listing listing = new Listing();
                listing.setListingId(Long.parseLong(rs.getString("listingId")));      
                listing.setSiteArea(rs.getString("siteArea"));   
                list.add(listing);
            }
           myrepo.saveAll(list);

}