axios 带验证参数上传

Posted Develon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了axios 带验证参数上传相关的知识,希望对你有一定的参考价值。

示例代码

前端:

        uploadFiles(state, uploadFile) {
            state.uploadFiles.forEach(it => {
                const f = it.file;
                if (uploadFile.name == f.name && uploadFile.size == f.size) {
                    throw ‘此文件已存在‘;
                }
            });
            var fileWrapper = {
                file: uploadFile,
                uploading: true,
                progress: 0,
            };
            var index = state.uploadFiles.push(fileWrapper);
            var form = new FormData();
            form.append(‘auth‘,
                new Blob([localStorage.getItem(‘auth‘)],
                    { type: "application/json", },
                ),
            );
            form.append(‘file‘, uploadFile); // or fileWrapper.file
            api.post(‘resource/upload‘, form, {
                headers: {
                        // "Content-Type": undefined,
                },
                // 上传进度事件
                onUploadProgress: progressEvent => {
                    console.log({loaded: progressEvent.loaded, total: progressEvent.total});
                    let complete = (progressEvent.loaded / progressEvent.total * 100 | 0);
                    fileWrapper.progress = complete;
                },
            }).then(res => {
                console.dir(res.data);
            }).catch(err => {
                console.dir(err);
                fileWrapper.progress = -1;
            });
            console.log(‘上传文件‘);
            console.dir(uploadFile);
        },

后端:

    @PostMapping("upload")
    private fun liveRequest(@RequestPart file: MultipartFile, @RequestPart auth: Auth): Any {
        test(author!!.auth(auth))
        log.d("用户上传文件", file.originalFilename)
        file.transferTo(File("${ uploadDir }/file"))
        log.d("用户上传文件", file.originalFilename, "保存成功")
        return "OK"
    }

参考

https://stackoverflow.com/questions/21329426/spring-mvc-multipart-request-with-json

以上是关于axios 带验证参数上传的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

Vue.js - 当标头中使用 multipart/form-data 时,axios 中的文件上传验证失败

JSP 设计教师与学生不同登陆界面(带验证码)

vue+axios通过formdata提交参数和上传文件