Я пытаюсь загрузить файл с помощью 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();
}
}
}
}