springboot上传文件(upload)(前端vue,后端springboot,以csv文件为例,进行解析并写入数据库)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Megustas_JJC/article/details/85240787

前端实现:
可以使用iView组件,实现文件的选择与上传,话不多说,直接上代码(注意,action中的路径及后端接收的路径,name即@RequestParam,通过name后端获取相应文件):

<template>
    <div>
        <Upload
            action="/test"
            name = "etymon"
            :on-success="onFileSuccess"
        >
            <Button icon="ios-cloud-upload-outline">词根同步</Button>
        </Upload>

        <div class="default">
            <Table :columns="columns" :data="data"></Table>
            <div style="margin: 10px;overflow: hidden">
                <div style="float: right;">
                    <Page :total="total" :current="current" @on-change="changePage"></Page>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "sync",
        methods: {
            onFileSuccess(res, file, fileList) {
                this.uploadPercent = 100
                this.data = res.data
                this.total = res.data.size
            },
            changePage(page) {
                this.current = page
                this.getLobs()
            }
        },
        data(){
            return{
                total:0,
                current:1,
                columns: [
                    {
                        title: '业务线',
                        key: 'lobId',
                    },
                    {
                        title: '中文名',
                        key: 'cnName',
                    }, {
                        title: '英文名',
                        key: 'enName',
                    }
                ],
                data: []
            }
        }
    }
</script>

<style scoped>

</style>

后端springboot可以通过MultipartFile对传输的文件进行接收,MultipartFile的进行pom引入及Configuration的配置即可:

@Configuration
public class FileUploadConfiguration {
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制 ,超出设置页面会抛出异常信息,
        // 这样在文件上传的地方就需要进行异常信息的处理了;
        factory.setMaxFileSize("1024MB"); // KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("1024MB");
        // Sets the directory location where files will be stored.
        // factory.setLocation("路径地址");
        return factory.createMultipartConfig();
    }
}

这样就可以在Controller直接通过MultipartFile对前端传来的文件进行接收及相关处理操作:

@RestController("/test")
public class FileUploadController {

    @Autowired
    private EtymonService etymonService;

    @PostMapping
    public List<Etymon> upload(@RequestParam("etymon") MultipartFile multipartFile) throws IOException{
        if (!multipartFile.isEmpty()) {
            File convFile = new File(multipartFile.getOriginalFilename());
            Integer lobId = Integer.valueOf(convFile.getName().replace(".csv", ""));
            convFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(convFile);
            fos.write(multipartFile.getBytes());
            fos.close();
            List<String[]> list = readCsvFile(convFile);
            List<Etymon> etymons = new ArrayList<>();
            for (String[] fields : list) {
                Etymon etymon = Etymon.builder().lobId(lobId).cnName(fields[0])
                    .enName(fields[1])
                    .tag(fields[3])
                    .description(fields[4].equals("") ? null : fields[4]).build();
                etymon.setCreatedBy(fields[2]);
                etymons.add(etymon);
            }
            // 数据库操作,写入数据
            return etymonService.bulkSave(etymons, UserUtils.getUser().getLogin());
        }
        return null;
    }
}

此处以csv格式的文件为例子,因此在MultipartFile获取到文件之后,需要对文件进行解析,解析出相关字段,写入数据库,对于csv文件的解析,我们可以使用opencsv,pom引入相关配置即可使用:

            <dependency>
                <groupId>com.opencsv</groupId>
                <artifactId>opencsv</artifactId>
                <version>${opencsv.version}</version>
            </dependency>

对opencsv相关操作的封装:

public class CsvFileUtil {

    private CsvFileUtil() {
    }

    public static List<String[]> readCsvFile(File csvFile) throws IOException{
        List<String[]> list = new ArrayList();
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(csvFile);
            bufferedReader = new BufferedReader(fileReader);
            CSVReader csvReader = new CSVReader(bufferedReader);
            list = csvReader.readAll();
        } catch (IOException e) {
            throw e;
        } finally {
            bufferedReader.close();
        }
        return list;
    }
}

至此,一个前端选择文件上传,后端对文件进行解析并写入数据库的功能就开发完成了,实现效果:
(1)界面
在这里插入图片描述

(2)点击button,选择文件并上传
在这里插入图片描述

(3)后台处理数据,并将写入数据库的数据返回,在前端进行展示

例如平时的数据导入,数据迁移等相关工作都可以通过这种界面化的方式而实现(emmmm,一定有的人还是觉得直接写个脚本更方便些,233333333)

猜你喜欢

转载自blog.csdn.net/Megustas_JJC/article/details/85240787