0

I try to upload file from page using axios and can't get it on my controller. In fromt-end I use Vue.js with axios, and at the back end Spring MVC Controller. It seems that my controller can`t convert FormData() to MultipartFile in spring. I read a lot of questions but have no answer. here is my code:

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

and controller file:

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();


    }


}

I will be very grateful for the advice.

P.S. when I use @RequestParam(name="file", required=true) MultipartFile file I get error POST http://localhost:8080/single-file 400 (Bad Request), It looks like spring cannot get MultipartFile file from FormData. At back end I don't get any errors, only MultipartFile file = null

1 Answer 1

1

After two days, that I spent to solve my promlem I fount a couple of working projects, compare all files and found, that my problem was in dependencies, I used dependency:

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

And when I change dependency:

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

Now it's working exactly how I need.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.