从react和spring boot上传csv文件

vtwuwzda  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(553)

也许任何人都知道如何解决将文件上传到后端的问题。从 Postman 发送文件看起来像,但从react上传后,我有如下异常:
2020-11-09 18:17:38.829调试10764---[nio-8081-exec-7]o.s.web.servlet.dispatcherservlet:post“/api/employees/save from csv”,参数={masked}2020-11-09 18:17:38.829调试10764---[nio-8081-exec-7]s.w.s.m.a.requestmappinghandlermapping:Map到com.bank.controller.employeecontroller#上传文件(multipartfile,model)2020-11-09 18:17:38.831调试10764---[nio-8081-exec-7].w.s.m.m.a.servletinvaccablehandlerMethod:无法解析public org.springframework.http.responseentity<com.bank.message.responsemessage>com.bank.controller.employeecontroller.uploadfile(org.springframework.web.multipart.multipartfile)中的参数[0],org.springframework.ui.model)抛出java.io.ioexception:所需请求部分“file”不存在2020-11-09 18:17:38.831调试10764---[nio-8081-exec-7].m.a.exceptionhandlerexceptionresolver:使用@exceptionhandler com.bank.exceptions.fileuploadexceptionadvice#handleexception(异常,webrequest)2020-11-09 18:17:38.832调试10764---[nio-8081-exec-7]o.s.w.s.m.m.a.httpentitymethodprocessor:与[application/json,text/plain,/]不匹配,支持:[]2020-11-09 18:17:38.833 warn 10764---[nio-8081-exec-7].m.a.exceptionhandlerexceptionresolver:已解析[org.springframework.web.multipart.support.missingservletrequestpartexception:所需的请求部分“文件”不存在]2020-11-09 18:17:38.837 debug 10764---[nio-8081-exec-7]o.s.web.servlet.dispatcherservlet:已完成400个错误的\u请求
此代码用于从react窗体发送文件:

class UploadFiles extends Component{

state = {
    file : ''
};

componentDidMount = () => {
    const {file} = this.props;
    this.setState({ file })
};

uploadFile = ({target : {files}}) => {
    console.log(files[0]);
    let data = new FormData();
    data.append('file', files);

    axios.post("/api/employees/save-from-csv", data)
        .then(res => {console.log(res)})
};

render(){
    return(
        <div className="container">
            <div className="row">
                <div className="col-md-6">
                    <div className="form-group files color">
                        <label>Upload Your File </label>
                        <input type="file" onChange={this.uploadFile}/>
                    </div>
                </div>
            </div>
        </div>
    )
}}

服务

public void csvToEmployees(@RequestParam("file") MultipartFile file, Model model) {
    // validate file
    if (file.isEmpty()) {
        model.addAttribute("message", "Please select a CSV file to upload.");
        model.addAttribute("status", false);
    } else {

        try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {

            CsvToBean csvToBean = new CsvToBeanBuilder(reader)
                    .withType(Employee.class)
                    .withIgnoreLeadingWhiteSpace(true)
                    .build();

            List users = csvToBean.parse();
            employeeRepository.saveAll(users);

            model.addAttribute("users", users);
            model.addAttribute("status", true);

        } catch (Exception ex) {
            model.addAttribute("message", "An error occurred while processing the CSV file.");
            model.addAttribute("status", false);
        }
    }

}

控制器

@PostMapping("/employees/save-from-csv")
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file, Model model) throws IOException {
    ResponseEntity<ResponseMessage> result = null;
    boolean finished = false;
    String message = "";

    if (CSVHelper.hasCSVFormat(file)) {
        try {
            service.csvToEmployees(file, model);
            message = "Uploaded the file successfully: " + file.getOriginalFilename();
            result = ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
            finished = true;
        } catch (Exception e) {
            message = "Could not upload the file: " + file.getOriginalFilename() + "!";
            message += e;
            result = ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(new ResponseMessage(message));
            finished = true;
        }
    }
    if (!CSVHelper.hasCSVFormat(file)){

        message = "File is empty!";
        result = ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseMessage(message));
    }
    if (!finished) {
        message = "Please upload a csv file!";
        result = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
    }
    return result;
}

CSV帮助器

public class CSVHelper {

    public static boolean hasCSVFormat(MultipartFile file) {

        String TYPE = "text/csv";
        return TYPE.equals(file.getContentType());
    }

    public static List<Employee> csvToEmployees(InputStream is) {
        try (BufferedReader fileReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
             CSVParser csvParser = new CSVParser(fileReader,
                     CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreHeaderCase().withTrim());) {

            List<Employee> employees = new ArrayList<>();

            Iterable<CSVRecord> csvRecords = csvParser.getRecords();

            for (CSVRecord csvRecord : csvRecords) {
                Employee employee = new Employee(
                        Long.parseLong(csvRecord.get("Id")),
                        csvRecord.get("Name"),
                        Long.parseLong(csvRecord.get("DepartmentId")),
                        Double.parseDouble(csvRecord.get("Salary")),
                        csvRecord.get("City"),
                        csvRecord.get("Street"),
                        csvRecord.get("BankName"),
                        csvRecord.get("CardNumber")
                );

                employees.add(employee);
            }

            return employees;
        } catch (IOException e) {
            throw new RuntimeException("fail to parse CSV file: " + e.getMessage());
        }
    }

}

单元测试

@Test
    public void saveEmployeesFromCSV() throws Exception {
        String url = "/api/employees/save-from-csv";

        String csvBuilder = "name,departmentId,salary,city,street,bankName,cardNumber\n" +
                "Maxim,1,3855,Madrid,Street,Bank York,NY98675432100\n";
        InputStream is = new ByteArrayInputStream(csvBuilder.getBytes());

        MockMultipartFile mockFile = new MockMultipartFile("file", "employees.csv", "text/csv", is);

        MockHttpServletResponse responseMessage = mvc.perform(MockMvcRequestBuilders.multipart(url)
                .file(mockFile)
                .param("file", "employees2.csv"))
                .andReturn()
                .getResponse();
        assertEquals(responseMessage.getStatus(), 200);
    }
q9yhzks0

q9yhzks01#

好吧,这花了我一些时间,虽然这是你犯的一个很小的错误。
在react代码中,设置文件数组,该数组作为 file 在你的 FormData .
这里正确的做法是只将数组的一个文件设置为 FormData :

uploadFile = ({target : {files}}) => {
    console.log(files[0]);
    let data = new FormData();
    data.append('file', files[0]); <- this here is where the error was

    axios.post("/api/employees/save-from-csv", data)
        .then(res => {console.log(res)})
};

相关问题