【问题标题】:Cannot upload file to Spring Boot REST using Axios and FormData无法使用 Axios 和 FormData 将文件上传到 Spring Boot REST
【发布时间】:2020-06-02 13:57:39
【问题描述】:

我尝试使用 axios 从页面上传文件,但无法在我的控制器上获取它。 在 fromt-end 中,我使用带有 axios 的 Vue.js,并在后端使用 Spring MVC 控制器。看来我的控制器无法在春季将 FormData() 转换为 MultipartFile。我读了很多问题,但没有答案。这是我的代码:

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- Vue.js development version, includes helpful console warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <!--Axios dependency-->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <!--Bootstrap-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

</head>
<body>
    <h4>Uploading files with Vue.js</h4>

    <div id="uploadSingle" class="container">

            <h5>Single file uploading</h5>
            <div class="large-12 medium-12 small-12 cell">

                <div class="form-row" >
                    <div class="col-md-4 mb-3">
                        <input type="file" ref="file" id="customFile"
                               v-on:change="handleFileUpload($event)"
                               class="custom-file-input"
                               enctype="multipart/form-data">
                        <label class="custom-file-label" for="customFile">{{chosenFile}}</label>
                    </div>
                </div>
                <button v-on:click="submitFile()" class="btn btn-primary">Submit</button>
            </div>
    </div>


    <div id="uploadMultiple" class="container">
        <h5>Multiple files uploading</h5>
    </div>


    <script >
        var app = new Vue({
            el: '#uploadSingle',
            data() {
                return {
                    message: 'Hello Vue!',
                    singleFile: '',
                    refFile: '',
                    chosenFile: 'Chose file'
                };
            },
            methods:{
                handleFileUpload(event){
                    this.singleFile = event.target.files[0];
                    this.chosenFile=this.singleFile.name;
                },
                submitFile(){
                    var formData = new FormData();
                    formData.append("file", this.singleFile);

                    axios.post( '/single-file',
                        formData,{
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }

                        }
                    ).then(function(){console.log('SUCCESS!')})
                        .catch((error) => console.log( error ) )

                },
            },
        })
    </script>
</body>
</html>

和控制器文件:

package com.yurets_y.webdevelopment_uploading_file_with_vue.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@CrossOrigin("*")
@Controller
public class UploadController {

    @Value("${upload.path}")
    private String uploadPath;


    @ResponseBody
    @PostMapping(value="/single-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> uploadSingle(
            @RequestParam(name="file", required = false) MultipartFile file
    ) {
        System.out.println("uploaded");
        System.out.println(file);


        return ResponseEntity.ok().build();


    }


}

我将非常感谢您的建议。

附: 当我使用 @RequestParam(name="file", required=true) MultipartFile 文件时,我收到错误 POST http://localhost:8080/single-file 400 (Bad Request),看起来 spring 无法从 FormData 获取 MultipartFile 文件。在后端我没有收到任何错误,只有 MultipartFile file = null

【问题讨论】:

    标签: spring spring-mvc vue.js post axios


    【解决方案1】:

    两天后,我花时间解决了我的问题,我找到了几个工作项目,比较了所有文件,发现我的问题出在依赖项上, 我使用了依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>
    

    当我改变依赖时:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    

    现在它完全按照我的需要工作了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2019-06-08
      • 2021-01-22
      • 2020-10-18
      • 2021-09-24
      • 2019-04-06
      相关资源
      最近更新 更多