0

I'm trying to upload a file with React and SpringBoot, but I keep on getting an error 404 and as a new user to both React and SpringBoot, I can't quite put my finger on what's the problem.

Here is my front-side (upload.js):

import React, {Component} from 'react';
import { Button, Form, Input, FormGroup} from 'reactstrap';
import axios from 'axios'

class Upload extends React.Component {
  state = {
    fileToSend:  null
  }

  handleSubmit = event => {
    event.preventDefault();

    axios.post('http://localhost:8080/upload', {
      fileToSend: this.state.fileToSend
    }).then(res => {
      window.location = "/home";
    })
  }

  render() {
    return (
      <div>
        <h1>{"Submit page"}</h1>
        <Form onSubmit={this.handleSubmit} encType="multipart/form-data" id="fileUploadForm">
          <FormGroup>
            <Input type="file" id="fileToSend"  name="fileToSend" accept=".pdf, .doc, .docx" multiple={false} required></Input>
          </FormGroup>
          <FormGroup>
            <Button type="submit" id="submitButton">{"Submit"}</Button>
          </FormGroup>
                </Form>
      </div>
    );
  }
}

export default Upload;

And here is my code on the back-end side: (FileUploadController.java)

package com.cal.stagemanager.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cal.stagemanager.service.FileService;


@RestController
@CrossOrigin
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public void uploadFile(@RequestBody MultipartFile[] files) {
        fileService.uploadFile(files);
    }

}

And, at last, FileService.java:

package com.cal.stagemanager.service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileService {
    @Autowired
    private static String uploadDirectory = System.getProperty("user.dir")+"/uploads";

    public void uploadFile(MultipartFile[] files) {
        StringBuilder fileNames = new StringBuilder();
        for (MultipartFile file : files) {
            Path fileNameAndPath = Paths.get(uploadDirectory, file.getOriginalFilename());
            fileNames.append(file.getOriginalFilename()+" ");
            try {
                Files.write(fileNameAndPath, file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }   
    }

}
bnm333
  • 1
  • 2

1 Answers1

0

When you are trying to send a file using

handleSubmit = event => {
    event.preventDefault();

    axios.post('http://localhost:8080/upload', {
      fileToSend: this.state.fileToSend
    }).then(res => {
      window.location = "/home";
    })
  }

You will send only the JSON.

So, to send a file it's a better idea to use FormData.

var bodyFormData = new FormData();
bodyFormData.append('fileToSend', imageFile);  // we can use .append to add a file
axios({
  method: 'post', // Declare the method
  url: '/upload',
  data: bodyFormData,
  config: { headers: {'Content-Type': 'multipart/form-data' }} // declare the kind of data
})
.then(function (response) {
    console.log(response); // handle success
})
.catch(function (response) {
    console.log(response); // something went wrong
});

Here: axios post request to send form data you can find some additional information about how to work with FormData in axios.

Nik
  • 2,170
  • 1
  • 14
  • 20