【问题标题】:Uploading image with Spring Boot使用 Spring Boot 上传图像
【发布时间】:2017-10-26 07:28:30
【问题描述】:

我正在使用 Thymeleaf 和 Spring boot 将图像上传到数据库。 我采取的第一步是创建上传页面和控制器方法以获取 MultipartFile(image) 作为字节数组。

这是我没有得到正确字节数组的地方。

百里香部分的代码:

<div class="col-sm-8">
  <form action="#" th:action="url to the controller method" method="post" enctype="multipart/form-data">

    <div class="form-group">
      <div class="col-md-2">
        <label for="image">Upload image</label>
      </div>
      <div class="col-md-8">
        <input id="image" type="file" name="image"/>
      </div>
    </div>

    <button type="submit" class="btn btn-default">Submit</button>
  </form>
</div>

这是我的 Spring 启动控制器:

@RequestMapping(value = "url to the controller method", method = RequestMethod.POST)
public String createImage(@RequestParam("image") MultipartFile image) {

    try {
        byte[] design = image.getBytes();

        System.out.println(design.toString());

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "redirect:/home";
}

我的 to 字符串返回:

[B@4fe2fee8

这似乎不是正确的值,因为当我在互联网上转换同一张图像时,我会得到一长串 0 和 1 的列表。

有人知道如何解决这个问题吗?我的多部分文件似乎不包含上传的图片。

我在表单操作中的 url 似乎是正确的,因为我可以在控制器中访问我的 Post 方法。

编辑

使用 image.isEmpty() 检查我的控制器中的 MultipartFile 是不正确的。

【问题讨论】:

  • 当您在数组上运行 println 时,您将打印对象而不是其内容。您是否调试并检查了数组包含的内容?
  • 不要理会toString 返回的奇怪值,默认实现只是返回类似于 @ 的东西,就像你看到的那样。

标签: java spring spring-mvc thymeleaf


【解决方案1】:

toString 不打印字节数组的内容。 Object.toString 的 Java 文档说明如下:

Object 类的 toString 方法返回一个字符串,该字符串由对象作为其实例的类的名称、at 符号字符“@”和对象哈希码的无符号十六进制表示形式组成。

这正是显示的内容。该数组包含所有你0和1。你可以轻松地将内容写入文件并打开它以查看它是否是正确的图像。

Files.write(Paths.get("image.jpg"), image.getBytes());

【讨论】:

    【解决方案2】:

    您可以使用Arrays.stream(design).forEach(System.out::println)打印内容。

    【讨论】:

      【解决方案3】:

      如果你想检查图像数据是否为空,你可以这样做:

      if (design.length == 0) {
        System.out.println("design is empty");
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-27
        • 2016-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-09
        • 1970-01-01
        • 2017-01-20
        相关资源
        最近更新 更多