首页 > 解决方案 > 尝试使用 React 和 SpringBoot 上传文件时出现错误 404

问题描述

我正在尝试使用 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);
    }

}

最后,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();
            }
        }   
    }

}

标签: javascriptjavareactjsspring-bootupload

解决方案


当您尝试使用发送文件时

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 post request to send form data你可以找到一些关于如何在 axios 中使用 FormData 的附加信息。


推荐阅读