无法使用Axios和FormData将文件上传到Spring Boot REST

问题描述 投票:0回答:1

我尝试使用axios从页面上载文件,但无法在控制器上获取它。在前端,我将Vue.js与axios一起使用,并在后端使用Spring MVC Controller。看来我的控制器无法在春季将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/[email protected]/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();


    }


}

我将非常感谢您的建议。

P.S。当我使用@RequestParam(name =“ file”,required = true)MultipartFile文件时,出现错误POSThttp://localhost:8080/single-file400(错误请求),看来spring无法从FormData获取MultipartFile文件。在后端我没有任何错误,只有MultipartFile file = null

spring spring-mvc vue.js post axios
1个回答
0
投票
  • 您在JavaScript端遇到任何错误吗?
  • Spring具有默认的可接受文件大小。您归档了哪个文件大小?
  • 您可以测试@PostMapping(path = "/single-file", headers = "content-type=multipart/*")
  • 将@RequestParam的name更改为value
© www.soinside.com 2019 - 2024. All rights reserved.