vue+springboot+el-uolpad组件实现文件上传

Vue+Springboot+el-upload组件实现文件手动上传

1.前端Vue + Element-UI库的el-upload组件 + axios发送请求

  • el-upload组件代码

    action属性为自动上传时的请求发送地址,此处无用

    auto-upload属性为false,即需要手动点击按钮进行上传

    accpent属性可以限制上传文件类型,直接填入后缀名即可

    file-list属性为当前待上传文件列表

<el-upload
           ref="upload"
           :action="uploadURL"
           accept=".csv"
           :file-list="fileList"
           :auto-upload="false">
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="uploadFile">
        上传到服务器
    </el-button>
    <div slot="tip" class="el-upload__tip">只能上传.CSV文件,且不超过10MB</div>
</el-upload>
  • uploadFile方法
uploadFile: function () {
    // 通过this.$refs.upload获取到上传内容
    let content = this.$refs.upload;
    // 默认只上传文件列表中的第一个文件
    // uploadFiles数组里的file还不能直接发送给后端  
    let file = content.uploadFiles[0];
    var formData = new FormData();
    // 填充进formdata的文件必须是原生file,否则后端接收不到  
    formData.append('file', file.raw);
    // 发起上传请求(axios需自己import到对应页面)
    axios({
        url: '/api/file/upload',
        method: 'post',
        headers: {
            // axios默认Content-Type为json/text,配置为multipart/form-data
            'Content-Type': 'multipart/form-data; '
        },
        data: formData
    }).then((response) => {
        // 上传成功后,清空待上传文件列表  
        this.$refs.upload.clearFiles();
        this.$message({
            message: '上传成功',
            type: 'success'
        });
    })
}

2.后端Springboot控制器接收axios请求

@RestController
@RequestMapping("api/file")
public class FileController {
    @PostMapping("/upload")
    public String import(@RequestParam(name = "file") MultipartFile file) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String filePath = "src/main/resources/upload/" + fileName;
        // 在resources/upload文件夹中创建名为fileName的文件
        OutputStreamWriter op = new OutputStreamWriter(new FileOutputStream(filePath), "UTF-8");
        // 获取文件输入流
        InputStreamReader inputStreamReader = new InputStreamReader(file.getInputStream());
        char[] bytes = new char[1024];
        // 开始写入
        while (inputStreamReader.read(bytes) != -1) {
            op.write(bytes);
        }
        // 关闭输出流
        op.close();
        // 关闭输入流
        inputStreamReader.close();
        return "上传成功";
    }
}

3.踩坑记录

一开始在前端页面上传文件,一直报500错误,后端报错信息显示接收不到file参数,如下图。但是用postman测试,发现接口能正常接收动文件,遂百思不得其解。最后终于发现uploadFile数组中的file并不是原生file,需要的是file.raw,于是问题解决。

image

posted on 2020-02-18 23:11  JavaCoder567  阅读(376)  评论(0编辑  收藏  举报

导航