简体   繁体   English

如何从Multipart文件中读取下载的文件(xml,txt),并将该数据逐行保存到数据库中

[英]How to read the downloaded file (xml, txt) from a Multipart file and save this data line by line to the database

I'm just learning Java(spring boot), but I need to make a small project like this. 我只是在学习Java(spring boot),但我需要做一个像这样的小项目。 I need to upload a file (xml, txt) to the server, read it line by line and put it in the database (in the table there is a field - body (type string) to put the contents of the downloaded file there. 我需要将一个文件(xml,txt)上传到服务器,逐行读取并将其放入数据库(在表中有一个字段 - 正文(类型字符串),用于将下载文件的内容放在那里。

I implemented the file upload to the server (line reading too), but I cannot put this data in the database. 我实现了文件上传到服务器(行读也行),但我不能把这些数据放在数据库中。 The downloaded file has a variable "complete Data" which contains the data of the downloaded file. 下载的文件具有变量“完整数据”,其中包含下载文件的数据。 How to pass it to the variable "body", so that it is stored in the database? 如何将它传递给变量“body”,以便它存储在数据库中? Or how to do it differently? 或者如何区别对待?

I found examples of how to put in the database the file itself, but I need to put the contents of the file (the internal text). 我找到了如何在数据库中放入文件本身的示例,但我需要放置文件的内容(内部文本)。

/*File download*/

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody String handleFileUpload(@RequestParam("name")String name,
                                                 @RequestParam("file")MultipartFile file){
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();

                String completeData = new String(bytes);

                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return completeData;
//              return "Вы удачно загрузили " + name + " B " + name + "-uploaded !";
            } catch (Exception e) {
                return "Вам не удалось загрузить " + name + " => " + e.getMessage();
            }
        }else{
            return "Вам не удалось загрузить " + name + " потому что файл пустой.";
        }
    }

/*Domain*/
public class Docs {
    private String body;

    public Docs(){
        super();
    }
        public Docs(String body){
        super();
        this.body=body;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}

I passed my variable "complete Data" to dao.addFile 我将变量“complete Data”传递给dao.addFile

dao.add(completeData);

Dao.class: Dao.class:

public void add_b_utmdocs(string body){
        template.update ("insert into docs (body) values (?)", body);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM