当前位置: 首页 > 知识库问答 >
问题:

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

郑正阳
2023-03-14
<!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(错误请求),看起来spring无法从FormData获得MultipartFile文件。在后端,我没有得到任何错误,只有MultipartFile文件=null

共有1个答案

文建业
2023-03-14

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

    <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>

现在它正按我需要的方式运作。

 类似资料:
  • 我的nexus公开了一个REST API来上传文件。通过curl,我可以使用以下命令上传: 卷曲-X柱“http://myurl:9086/service/rest/v1/components?repository=ebooks-store“-H”accept:application/json“-H”内容类型:multipart/form data“-F”raw。目录=测试“-F”原始。asset

  • 我正在努力使用axios将xml文件上载到我的asp。net服务器。我正在使用vue端的以下代码获取一个xml文件,该文件正在工作,然后将其上载到我的服务器: 在asp。net端我得到了这个函数: 上载文件会导致代码415:不支持的媒体类型。 我找到了一些建议将xml格式化程序添加到我的项目中,这不起作用,而且我不想解析xml文件,我只想将文件保存到我的文件系统中。 我尝试将原始文件和解析的文本与

  • 这段javascript代码如下所示。注意,当file input元素的值发生变化时(即,一旦他们选择了要上传的文件),就会调用该命令 请原谅所有控制台日志。它的目的是显示输出和调试。 您将看到,我还附加了一个username字段,只是为了测试帖子是否在控制器中使用了一些完整的数据。的确是。以下是记录数组的输出: 有什么想法吗??

  • httpclient,HttpTime 4.1.3 我试图通过http将文件上载到远程服务器,但没有成功。 这是我的代码: 服务器是Solr。 这是为了替换像这样调用的工作bash脚本, <代码>卷曲http://localhost:8080/solr/update/extract?literal.id=bububu 如果我尝试设置“内容类型”“多部分/表单数据”,接收部分会说没有边界(这是真的)

  • 问题内容: 当我使用XMLHttpRequest时,使用可以正确上传文件。但是,当我切换到时,我的代码将中断。 这是有效的原始代码: 这是我失败的尝试: 我究竟做错了什么?如何使用AJAX正确上传文件? 问题答案: 您必须添加方法,以便jQuery不会更改标头或数据(这会破坏当前代码)。

  • 我想用cdn的axios 但是我得到了一个错误:拒绝加载脚本的https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'因为它违反了以下内容安全策略指令:“script src'self'”。请注意,未显式设置“script src elem”,因此将“script src”用作回退。