java 错误403 Sping Boot POST request when i'm trying to upload a picture into the server

von4xj4u  于 2023-06-20  发布在  Java
关注(0)|答案(1)|浏览(95)

所以,我试图插入照片到数据库,但我得到一个错误403命中.在POSTMAN中,当我检查端点时,一切工作正常,但当我创建axios请求时,错误出现了。
这是我在Spring的控制器:

@PostMapping(value = "/addItem/{id}",consumes ={"multipart/form-data"})
public void addItem(@RequestPart("item") Item item, @PathVariable Integer id, @RequestPart("imageFile") MultipartFile[] file) {
    try {
       System.out.println(item);
       System.out.println(id);
       System.out.println(file);
       Set<ImageModel> images = uploadImage(file);
       item.setItemImages(images);
       itemService.addItem(item, id);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

public Set<ImageModel> uploadImage(MultipartFile[] multipartFiles) throws IOException {
    Set<ImageModel> imageModels = new HashSet<>();
    for (MultipartFile file : multipartFiles) {
        ImageModel imageModel = new ImageModel(
              file.getOriginalFilename(),
              file.getContentType(),
              file.getBytes()
        );
        imageModels.add(imageModel);
    }
    return imageModels;
}

这是我在前端的请求,使用axios:

const formData = new FormData();
    const item = {
      name: name,
      size: size,
      condition: condition,
      price: price,
      description: description,
      itemImages: [],
    }
    formData.append('item', new Blob([JSON.stringify(item)], { type: 'application/json' }));
    formData.append('imageFile', images[0])


    try {
      await axios.post("http://localhost:8080/items/addItem/1", formData, {
        headers: {
          Authorization: `Bearer ${token}`,
          'Content-Type': 'multipart/form-data'
        },
      });
    } catch (err) {
      console.log(err);
    }
  }

有什么办法可以解决这个问题吗?我已经尝试了不同的方法为前端。我应该提到的是,图像是以字节数组的形式存储的。

umuewwlo

umuewwlo1#

我使用的将图像上传到Sping Boot 后端的方法是:
React代码:

var imgArray : any[]=[];

imgArray保存我想要发送到后端的图像列表,下面的代码将图像Map到formData。

imgArray.map((file:any,index) => {
formData.append("file1",file);
})

axios.post(api_image_url,formData,{
headers:{
'Content-Type': 'multipart/form-data'
}
}).catch((err) => {console.log("err : " + err)});

服务器端代码:

@PostMapping(consumes = "multipart/form-data")
public ResponseEntity<?> addImage(@RequestParam("file1") MultipartFile[] file1)
{
for (MultipartFile file : file1) {
// The code to store the images into DB goes here    }
}

相关问题