我想将文件和信息从React传递到Spring

vx6bjr1n  于 2023-03-22  发布在  Spring
关注(0)|答案(3)|浏览(115)

我想把文件和信息作为数据从React传递给Spring。但是我得到了Axios error 400ReactSpring代码有问题吗?我对Spring没有什么经验,所以我不确定我是否做对了。我应该如何移交文件和信息?有什么建议或解决方案吗?请?语言可能是奇怪的,因为它是由翻译写的。

React

const saveData = {
    boardWriter: sessionStorage.getItem("memberID"),
    boardTitle: title,
    boardContents: contents,
    boardFile: file,
  }
const write = () => {
    const formData = new FormData();

formData.append("boardWriter", sessionStorage.getItem("memberID"));
    
formData.append("boardTitle", title);
    
formData.append("boardContents", contents);
    
formData.append("boardFile", file);

    axios
      .post("http://localhost:8080/api/board/write", saveData, {
        headers: {
          "Content-Type": "multipart/form-data",
        }
      })
      .then(res => res.data)
      .catch(err => console.log(err));}

Spring
控制器

@PostMapping("/write")
    public void save(@RequestParam BoardDTO boardDTO,
                     @RequestParam MultipartFile file) throws IOException {
        
String fileName = file.getOriginalFilename();
        
file.transferTo(new File(fileName));
        
boardDTO.setBoardFile(fileName);
        
boardService.save(boardDTO);
  
}

仓库

public int save(BoardDTO boardDTO) {
        
return sql.insert("Board.save", boardDTO);
    
}

服务

public int save(BoardDTO boardDTO) {
        
return boardRepository.save(boardDTO);
    
}

mapper

<mapper namespace="Board">

    <insert id="save" parameterType="board">
        insert into board(boardWriter, boardTitle, boardContents, boardFile)
        values(#{boardWriter}, #{boardTitle}, #{boardContents}, boardFile=#{boardFile})
    </insert>
owfi6suc

owfi6suc1#

在控制器的“保存”方法中,将(value="boardFile")添加到“file”RequestParam中,就像下面一样,然后重试。

@PostMapping("/write")
    public void save(@RequestParam BoardDTO boardDTO,
                     @RequestParam(value="boardFile") MultipartFile file) throws IOException {
...
}
niknxzdl

niknxzdl2#

我正在做类似的事情,但使用Angular和Spring。
这是Angular中发送请求的代码示例:

runCase(runDetails?: RunDetails, dataDrivenFile?: File) {
    const formdata: FormData = new FormData();
    if (dataDrivenFile) {
      formdata.append('dataDrivenFile', dataDrivenFile);
    }
    if (runDetails) {
      formdata.append('runDetails', new Blob([JSON.stringify(runDetails)], {
        type: 'application/json'
      }));
    }

    const headers = new HttpHeaders({
      Accept: 'application/json'
    });

    return this.apiService.post(this.cloudConfigService.runCase(), formdata, headers);
  }

www.example.com的内容this.apiService.post如下:

post(path: string, body: any, customHeaders?: HttpHeaders): Observable<any> {
    return this.request(path, body, RequestMethod.Post, customHeaders);
  }

  private request(path: string, body: any, method = RequestMethod.Post, customHeaders?: HttpHeaders): Observable<any> {
    const req = new HttpRequest(method, path, body, {
      headers: customHeaders || this.headers,
      reportProgress: true,
      withCredentials: true
    });

    return this.http.request(req).pipe(
      filter(response => response instanceof HttpResponse),
      map((response: HttpResponse<any>) => response.body)
    );
  }

这是Spring中接受和处理该请求的代码的示例:

@PostMapping(value = APIConfig.RUN_CASE_URL)
public ResponseEntity runCase(
        @RequestPart(value = "dataDrivenFile", required = false) MultipartFile dataDrivenFile,
        @RequestPart("runDetails") RunDetails runDetails
) throws InterruptedException, IOException {
    runDetails.setDataDrivenFile(dataDrivenFile);

    runService.run(runDetails);
    
    return ResponseEntity.ok().build();
}

希望对你有帮助。

tag5nh1u

tag5nh1u3#

您可以按照我在previous answer中展示的方式来执行它,您可以找到有关如何执行here的更多详细信息,或者如果您愿意,您可以遵循最初的方法并进行一些小的修改:
更改此内容:

formData.append("boardFile", file);

改为:

formData.append("file", file);

或者,在Spring中,更改:

@RequestParam MultipartFile file

更改为:

@RequestParam MultipartFile boardFile

或:

@RequestParam(value="boardFile") MultipartFile file

在这一行,发送formData,而不是发送saveData

axios
      .post("http://localhost:8080/api/board/write", saveData, {

将其更改为如下所示:

axios
      .post("http://localhost:8080/api/board/write", formData, {

Spring中删除此行的**@RequestParam**:

public void save(@RequestParam BoardDTO boardDTO,

看起来是这样的:

public void save(BoardDTO boardDTO,

这应该能让它工作。当我复制你的代码并做这些修改时,它对我很有效。

相关问题