java - 使用 axios POST 请求将 JSON 数据作为 multipart/form-data 发送

标签 java reactjs spring-boot rest axios

以下 API 使用 postman 工作:

POST request that accepts from the backend

Spring boot,后端代码:

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@Slf4j
public class UploadFile {
    @Autowired
    private FTPClient con;

    @PostMapping("/api/auth/uploadfiles")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

        try {
            boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());

            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded " + file.getOriginalFilename() + "!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            redirectAttributes.addFlashAttribute("message",
                    "Could not upload " + file.getOriginalFilename() + "!");
        }
        return "redirect:/";
    }
}

ReactJS,前端代码:我在 this.state.ipData 中有对象数组。

  exportFTP = async () => {
    
      const fromdata = this.state.ipData;
      alert("Data Send to FTP server");

    axios({
      method: 'post',
      url: 'http://localhost:8080/api/auth/uploadfiles',
      data: fromdata,
      header: {
        'Accept': 'application/json ,text/plain, */*',
        'Content-Type': 'multipart/form-data',
        //'Authorization': 'Bearer '+JWTToken,
      },
    })
  }

触发功能的按钮:

<button
  style={{ marginRight: "2%", marginTop: "0.25%" }}
  type="button"
  className="btn btn-info"
  onClick={() => this.exportFTP()}
>
  Export to FTP
</button>

我需要将我的前端 (ReactJS) 代码更改为我使用 postman 执行 POST 请求时的代码。当前的 JS 代码导致以下错误响应:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause

请注意,API 在使用 Postman 时有效。 如何修复 JS 代码?

最佳答案

您在多部分请求中将 JSON 数据作为 Blob 发送。所以,你需要使用 Blob API。

创建一个函数以从 JSON 数据创建 blob:

function jsonBlob(obj) {
  return new Blob([JSON.stringify(obj)], {
    type: "application/json",
  });
}

并在请求中使用这个函数:

exportFTP = async () => {
  const formData = new FormData();
  formData.append("file", jsonBlob(this.state.ipData))

  axios({
    method: "post",
    url: "http://localhost:8080/api/auth/uploadfiles",
    data: formData,

    /* You had a Typo: it is "headers" not "header".
    And, multipart/form-data header should get set automatically 
    as we used FormData. You might not need to add that manually. */
    // You may also not need Accept header; (should be set automatically).
    
    headers: { 
      Accept: "application/json ,text/plain, */*",
      "Content-Type": "multipart/form-data",
      // 'Authorization': 'Bearer '+ JWTToken,
    },
  });
};

关于java - 使用 axios POST 请求将 JSON 数据作为 multipart/form-data 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66971829/

相关文章:

javascript - 在 ReactJS 中处理未定义值的最佳方式?

java - LocalDateTime 将无效日期解析为有效日期并且不抛出任何异常

javascript - setAttribute 不适用于 create-react-app 中的 onClick

jquery - 使用哪个 URL 从 React 组件调用 symfony 中的 API 函数,所有这些都在同一个应用程序中?

Java:将两个BigInteger对象分成一个BigDecimal对象

java - 如何检查生成的 Java 代码是否符合 Java 语言规范?

java - 如何从 spring boot gradle 插件 buildBootImage 切换到不同的 jdk 发行版

java - 具有多个 In 条件的 Spring CrudRepository 查询

java - jtable 到图像的转换未正确发生

Java 程序无法在 linux 中挂载的系统上写入