应用 springboot+axios+element-ui实现文件上传

springboot做为后台服务器
vue+element-ui做为前端
axios实现数据交互
实质原理利用了js中的FormData的API,参照了springboot 文件上传的思路

1.springboot后台程序

1.1 application.properties

设置单个文件限制为1M,同时上传限制10MB

server.port=8088
server.servlet.context-path=/neu_his
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB
1.2 处理器程序
@RestController
@RequestMapping("/upload")
public class FileUploadHandler {
    
    @RequestMapping("/photos")
    public List<String> uploadMutipartFile(MultipartFile[] photos, HttpServletRequest request) throws Exception {
        List<String> ps = new ArrayList<String>();
        if(photos == null) {
            ps.add("no files");
            return ps;
        }
        for(MultipartFile f : photos) {
            String old_name = f.getOriginalFilename(); //原始文件名
            String ext_name = old_name.substring(old_name.lastIndexOf(".")); //扩展名
            String new_name = UUID.randomUUID().toString()+ext_name; //利用UUID生成新文件名
            String path = request.getRealPath("/upload/photos"); //上传位置:工程/static/upload/photos
            File fx = new File(path);
            if(!fx.exists()) {
                fx.mkdirs();
            }
            File n = new File(fx, new_name);
            f.transferTo(n);
            ps.add(n.getPath());
        }
        return ps;
    }
}

2.element-ui项目

已经通过npm安装了axios和element-ui环境并做好相应配置,过程参照前面的文章

2.1 设置跨域支持

webpack.config.js中 devServer节点追加配置,
target:springboot服务器url
changeOrigin: true表示支持跨域访问
pathRewrite:可以理解为对tatget进行路径映射

'/neu_his/': {
        target: 'http://localhost:8088/neu_his',
        changeOrigin: true,
        pathRewrite: {
          '^/neu_his': ''
        }
}
2.2 vue核心代码

关于element-ui上传组件的官方API:https://element.eleme.cn/#/zh-CN/component/upload
action="" 文件上传位置,异步提交时不宜填写
:auto-upload="false" 设置手动提交
:limit="5" 文件个数限制
:on-preview="handlePictureCardPreview" 点击文件列表中已上传的文件时的钩子
:on-remove="handleRemove" 文件列表移除文件时的钩子
:on-change="fileChange" 文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
:multiple="true" 是否支持多文件上传
:file-list="fileList" 绑定的数据

<template>
    <div>
        <el-row>
            <el-col :span="12" :offset="6">
                <div id="demo">
                    <el-row>
                        <el-col :span="24">
                            <div>
                                <el-upload
                                  action=""
                                  list-type="picture-card"
                                  :auto-upload="false"
                                  :limit="5"
                                  :on-preview="handlePictureCardPreview"
                                  :on-remove="handleRemove"
                                  :on-change="fileChange"
                                  :multiple="true"
                                  :file-list="fileList">
                                  <i class="el-icon-plus"></i>
                                </el-upload>
                                <el-dialog :visible.sync="dialogVisible">
                                  <img width="100%" :src="dialogImageUrl" alt="">
                                </el-dialog>
                            </div>
                        </el-col>
                    </el-row>   
                    <el-divider></el-divider>
                    <el-row>
                        <el-col :span="3" :offset="15">
                            <el-button type="primary" class="btn_pos" @click="uploadImage">上传</el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    export default {
        data: function() {
            return {
                dialogImageUrl: '',
                dialogVisible: false,
                fileList: []
            };
        },

        methods: {
            handleRemove: function(file, fileList) {
                this.fileList = fileList;
            },
            fileChange: function(file, fileList){
                this.fileList = fileList;
            },
            handlePictureCardPreview: function(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            uploadImage: function(){
                let formData = new FormData();
                for(let i = 0; i < this.fileList.length; i++){
                    formData.append("photos", this.fileList[i].raw, this.fileList[i].name);
                }
                let config = {'Content-Type': 'multipart/form-data'};
                let this_obj = this;
                this.$axios.post('/neu_his/upload/photos', formData, config)
                    .then((res) => {
                        console.log(res.data);
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                
            }
        }
    }
</script>
<style scoped>
    .btn_pos{
        margin-top: 0px;
    }
</style>

推荐阅读更多精彩内容