尝试使用React和SpringBoot上载文件时出现错误404

时间:2018-10-20 17:28:11

标签: javascript java reactjs spring-boot upload

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

}

1 个答案:

答案 0 :(得分:0)

当您尝试使用

发送文件时
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的其他信息。

相关问题