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

时间:2021-04-06 15:37:48

标签: java reactjs spring-boot rest axios

以下 API 使用邮递员工作:

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) 代码更改为使用邮递员进行 POST 请求。当前 JS 代码导致以下错误响应:

<块引用>

Servlet.service() for servlet [dispatcherServlet] in context with path [] 抛出异常 [Request processing failed;嵌套异常是 org.springframework.web.multipart.MultipartException: Current request is not a multipart request] 具有根本原因

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

2 个答案:

答案 0 :(得分:3)

您在多部分请求中将 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,
    },
  });
};

答案 1 :(得分:2)

尝试去除头部并发送请求

    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
    }).then(function (res) {
      if (res.ok) {
        alert("Perfect! ");
      } else if (res.status == 401) {
        alert("Oops! ");
      }
    }, function (e) {
      alert("Error submitting form!");
    });
}
相关问题