spring 从 MultipartFile 读取数据,其中 csv 从浏览器上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33143743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:49:43  来源:igfitidea点击:

read data from MultipartFile which has csv uploaded from browser

springspring-mvccsv

提问by romil gaurav

May be I am doing it worng by using MultipartFile upload feature.

可能是我通过使用 MultipartFile 上传功能来实现的。

I have to read data from csv file which will be chosen by the client through the browser. I used MultipartFile to upload file. The file is coming to the controller but now I am unable to read csv data from it. Please guide the best way to do it or help me read csv data from MultipartFile. The jsp has

我必须从客户端通过浏览器选择的 csv 文件中读取数据。我使用 MultipartFile 上传文件。该文件正在进入控制器,但现在我无法从中读取 csv 数据。请指导最好的方法或帮助我从 MultipartFile 读取 csv 数据。jsp有

    <form method="POST" action="uploadFile" enctype="multipart/form-data">
            File to upload: <input type="file" name="file"> <input
                type="submit" value="Upload"> Press here to upload the
            file!
        </form>

The controller has

控制器有

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {

Thanks.

谢谢。

采纳答案by romil gaurav

I figured out a workaround. I converted the file to bytes and then converted the bytes to String. From String I applied string.split() to get what I wanted out of the file.

我想出了一个解决方法。我将文件转换为字节,然后将字节转换为字符串。从 String 我应用 string.split() 来从文件中得到我想要的东西。

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public String uploadFileHandler(@RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
            String completeData = new String(bytes);
            String[] rows = completeData.split("#");
            String[] columns = rows[0].split(",");

回答by cpxondo

I used a buffer to read line by line and get from multipart the inputstream. Maybe is more code, but I find helpful read text file by lines.

我使用缓冲区逐行读取并从多部分获取输入流。也许是更多的代码,但我发现逐行阅读文本文件很有帮助。

BufferedReader br;
List<String> result = new ArrayList<>();
try {

     String line;
     InputStream is = multipart.getInputStream();
     br = new BufferedReader(new InputStreamReader(is));
     while ((line = br.readLine()) != null) {
          result.add(line);
     }

  } catch (IOException e) {
    System.err.println(e.getMessage());       
  }