【问题标题】:Java Spring REST Api with images (files)带有图像(文件)的 Java Spring REST Api
【发布时间】:2021-06-17 18:29:40
【问题描述】:

我正在使用 Java Spring 和 MongoDB 创建一个 REST API。我有一个具有名称和价格等属性的模型,我希望用户能够将带有每个这些对象的图像上传到数据库中。所以我需要一种方法让 API 获取文件(图像)并将它们存储在服务器上并保存链接以访问数据库中的文件,以便用户能够通过获取请求获取链接以访问图像。

谁能给我一些关于如何使用 Java Spring 和 MongoDB 构建它的提示或资源? 如果您能给我一些帮助,我将不胜感激。

【问题讨论】:

    标签: java spring mongodb rest


    【解决方案1】:

    我不确定这是否是最佳做法。不过让我试试吧。

    // Use "multipart/form-data"
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity example(
    @RequestPart(value = "jsonData") String json, // a string in the form of json "{\"id\": 12}"
    @RequestPart(value = "image") MultipartFile image // an image file
    ) {
      try {
         // convert the json string into an object you define.
        ObjectMapper mapper = new ObjectMapper();
        [YOUR_JSON_OBJECT] hello = mapper.readValue(jsonString, [YOUR_JSON_OBJECT_HERE].class);
        // upload the file
        ...
        // save the object into the database
        ...
         return ResponseEntity.ok();
      } catch (JsonProcessingException e) {
         // if the string is a wrong form of json,
         return ResponseEntity.badRequest();
      }
    }
    

    希望你有提示。

    编码愉快!

    【讨论】:

      猜你喜欢
      • 2017-08-03
      • 2021-07-23
      • 2020-08-26
      • 2017-11-06
      • 2016-03-05
      • 2020-08-09
      • 2019-01-12
      • 2015-06-15
      • 2017-01-04
      相关资源
      最近更新 更多