【问题标题】:Sending MultipartFile and JSON object with POST method使用 POST 方法发送 MultipartFile 和 JSON 对象
【发布时间】:2021-06-03 01:07:21
【问题描述】:

我有他的 POST 方法,我想发送一个图像和一个 JSON 对象。 这是我的方法:

 @PostMapping("/saveCategory")
    @ResponseStatus(HttpStatus.OK)
    public void createCategory( @RequestParam("file") MultipartFile file, @RequestParam("id") CategoryModel s) {
        System.out.println(s);

        String fileName = fileStorageService.storeFile(file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/downloadFile/")
                .path(fileName).toUriString();
    //  category.setImage_path(fileName);

        //this.categoryRepository.save(category);

         /*return new UploadFileResponse(fileName, fileDownloadUri,
        file.getContentType(), file.getSize());*/

    }

这是我来自 POSTMAN 的发帖请求:-

我不明白我的问题出在哪里,是 POSTMAN 请求还是我的方法?

这是我的 CategoryModel:

 @Entity
@Table(name = "Category")
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class CategoryModel {
    @Id
    @Column(name = "id")
    //@GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String category_name;
    private String category_description;
    private String image_path;

    @JsonIgnore
    @OneToMany( mappedBy = "category")
    private Set<ProductModel> category;

【问题讨论】:

  • 显示您的班级类别模型
  • 错误似乎是因为 category_name 变量,spring 期望它是 Long 但你是从邮递员发送的字符串。请检查您是如何在代码中使用 category_name 的。
  • 你可以看到我的categoryModel。我的 category_name 变量是 String 但我的 id 是 Long。

标签: java spring-boot postman


【解决方案1】:

响应错误表明您期望的是 CategoryModel 类型的 id,但您发送的是 String 类型的 id。

FormData 主要用于发送表单数据。这有一个限制,您只能将文件或字符串作为键/值对而不是对象发送。

您可以将 id 重命名为 categoryName 并将“ziska111”作为值。在方法中,将@RequestParam("id") CategoryModel s替换为@RequestParam("categoryName") String categoryName

【讨论】:

    猜你喜欢
    • 2011-11-11
    • 2014-02-07
    • 1970-01-01
    • 2022-06-14
    • 2017-06-19
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    相关资源
    最近更新 更多