sql - 在 web 应用程序中保存图像文件,java
问题描述
在我的网络应用程序中,我希望允许“客户端用户”上传大量图像文件,并且“客户端用户”必须能够看到上传的图像文件网格。
在这种情况下,所有图像文件都有权进行上传、读取、删除和编辑操作。
基本上我正在使用java技术,但我有疑问,
- 进行这种巨大的图像文件管理最安全有效的方法是什么?
- 什么是最合适的技术堆栈,可以用于这种 Web 应用程序?
解决方案
转到此存储库并转到display-image-from-db
分支。基本方法如下:
在您拥有的实体中:
@Lob private Byte[] image;
ImageController.java
- 你通过一个MultipartFile
@PostMapping("recipe/{id}/image") public String handleImagePost(@PathVariable String id, @RequestParam("imagefile") MultipartFile file){ imageService.saveImageFile(Long.valueOf(id), file); return "redirect:/recipe/" + id + "/show"; }
调用
imageService
以保存file
作为参数传递的图像。该服务基本上将图像内容复制到一个字节数组,最后您将该字节数组分配给您的实体。
@Override @Transactional public void saveImageFile(Long recipeId, MultipartFile file) { try { Recipe recipe = recipeRepository.findById(recipeId).get(); Byte[] byteObjects = new Byte[file.getBytes().length]; int i = 0; for (byte b : file.getBytes()){ byteObjects[i++] = b; } recipe.setImage(byteObjects); recipeRepository.save(recipe); } catch (IOException e) { //todo handle better log.error("Error occurred", e); e.printStackTrace(); } }
对于完整的源代码,请转到 repo,这肯定会有所帮助。但是我强烈建议将文件存储在磁盘上而不是数据库中。数据库应该只存储文件的路径。对于这样的解决方案,这里有一个例子:link
TL;博士
干杯!
推荐阅读
- xml - 使用 XSL/XSLT 从同名的兄弟元素中选择一个子元素
- reactjs - Next JS getInitialProps 中缺少请求信息
- javascript - 如何在 AR 模式下放置 a-image 以使其旋转面向用户?
- opengl - 在 OpenGL 中使用多个光源时如何解决我的光照问题(片段着色器问题?)
- html - 每当我将它放在引导导航栏上时,svg 徽标格式都会发生变化
- python - 如何使用numpy将嵌套数组合并到维度更大的数组?
- javascript - Moment.JS 说日期在使用 .format() 时无效,但在使用 isvalid() 函数时有效我该如何解决这个问题?
- html - CSS内联网格:最宽元素的宽度设置兄弟元素的宽度
- android - Flutter 如何检查我的设备是否通过蓝牙连接到另一台设备
- java - 连接 oracle 11g 与 java 8 (eclipse)