我无法使用multipartFile在Spring Boot 中发送数据?

44u64gxh  于 2023-11-17  发布在  Spring
关注(0)|答案(1)|浏览(152)

我无法使用react with axios将数据发送到spring Boot 应用程序。我需要发送数据包,以便在其中包含JSON和要发送到后端的图像。我已经在后端创建了方法,错误告诉它不接受不支持的Content-Type 'application/octet-stream',但是在inspect元素中,它将其作为“multipart/form-data”发送。我尝试使用Postman,它成功地将数据发送到数据库,但是当我使用前端时,我无法做到这一点。下面是我在后端的方法:

@PostMapping("/meals")
public ResponseEntity<String> createMeal( MultipartFile [] file, @RequestPart("meal") Meal meal, @RequestPart(value = "image", required = false) MultipartFile imageFile) {    

Meal savedMeal = authService.saveMeal(meal, imageFile);
    if (savedMeal != null) {
        return ResponseEntity.ok("Meal created successfully.");
    } else {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating the meal.");

    }
}

 const [mealData, setMealData] = React.useState({
        name: '',
        calories: 0,
        protein:0,
        fat:0,
        description: '',
        image: null, // State to hold the selected image file
      });
 

 function handleImage(e){
    const image = e.target.files[0];
    setMealData({...mealData,image});
  }
  function handleChange(e) {
    const { name, value } = e.target;
    setMealData({ ...mealData, [name]: value });
  }

  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const meal = {
        name: mealData.name,
        description: mealData.description,
        protein: mealData.protein,
        fat: mealData.fat,
        calories: mealData.calories,
      };

      const formData = new FormData();

      formData.append("meal", JSON.stringify(meal));
      formData.append("image", mealData.image);

      console.log(JSON.stringify(meal));
      console.log(mealData.image);

      const res = await axios.post("http://localhost:8080/auth/meals", formData, {
        headers: {
          "Content-Type": "multipart/form-data", // Set the content type to multipart/form-data
        },
      });
    } catch (e) {
      console.log(e);
    }
  };

字符串
`

2izufjch

2izufjch1#

我已经用这种方式实现了很多次,我看不出有什么不同。
因此,如果没有完整的错误和代码,很难理解这个问题。但是你可以使用一些方法来尝试理解这个问题。
1.删除第一个参数(MultipartFile [] file
1.验证是否导入了正确的库(org.springframework.web.multipart.MultipartFile
1.尝试通过仅发送一个参数(文件)来隔离问题
1.请尝试以application.yaml为单位设置最大文件大小或发送小图像
1.禁用任何过滤器或拦截器

@PostMapping("/meals")
public ResponseEntity<String> createMeal(@RequestPart(value = "image", required = false) MultipartFile imageFile) {    
  
    InputStream stream = imageFile.getInputStream(); // For debug
    Meal savedMeal = authService.saveMeal(null, imageFile);
    if (savedMeal != null) {
       return ResponseEntity.ok("Meal created successfully.");
    } else {
       return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error creating the meal.");
    }
}

字符串
而在相同的UI中,只使用基本的:

const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const meal = {
        name: mealData.name,
        description: mealData.description,
        protein: mealData.protein,
        fat: mealData.fat,
        calories: mealData.calories,
      };

      const formData = new FormData();

      //formData.append("meal", JSON.stringify(meal));
      formData.append("image", mealData.image);

      console.log(JSON.stringify(meal));
      console.log(mealData.image);

      const res = await axios.post("http://localhost:8080/auth/meals", formData, {
        headers: {
          //"Content-Type": "multipart/form-data", // Set the content type to multipart/form-data
        },
      });
    } catch (e) {
      console.log(e);
    }
  };


好运

相关问题