Ошибка 404 при попытке загрузить файл с помощью React и SpringBoot - PullRequest
0 голосов
/ 20 октября 2018

Я пытаюсь загрузить файл с помощью React и SpringBoot, но получаю сообщение об ошибке 404, и как новый пользователь для React и SpringBoot я не могу понять, в чем проблема.

Вот моя лицевая сторона (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;

А вот мой код на задней стороне: (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);
    }

}
* 1008И, наконец, 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();
            }
        }   
    }

}

1 Ответ

0 голосов
/ 20 октября 2018

Когда вы пытаетесь отправить файл, используя

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

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

Вы отправите только JSON.

Итак, для отправки файла лучше использовать 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
});

Здесь: отправка запроса axios для отправки данных формы вы можете найти дополнительную информациюо том, как работать с FormData в axios.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...