java - 如何在 spring 中将图像转换为多部分文件

标签 java spring image

我有一个图像文件并使用该图像创建 File 对象

File file = new File("E://Shared Data/Images/xyz.jpg");

上面的行创建了一个file对象,其大小如440272,我需要将上面的图像文件转换为多部分文件我所做的

DiskFileItem fileItem = new DiskFileItem("file", "image/png", false, file.getName(),
                                    (int) file.length(), file.getParentFile());
                            fileItem.getOutputStream();
                            MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                            adminAssetUploadController.upload(request, multipartFile, "product", null);

问题是转换后我得到的是size=0,而不是得到像440272这样的size。如果我获得imagesize,以便我可以通过将其传递给upload方法将其存储到某个位置。

下面是上传方法

public ResponseEntity<Map<String, Object>> upload(HttpServletRequest request,
            @RequestParam("file") MultipartFile file, @PathVariable(value = "sectionKey") String sectionKey,
            @PathVariable(value = "id") String id) throws IOException {
        Map<String, Object> responseMap = new HashMap<String, Object>();

        Map<String, String> properties = new HashMap<String, String>();
        properties.put("entityType", sectionKey);
        properties.put("entityId", id);

        StaticAsset staticAsset = staticAssetService.createStaticAssetFromFile(file, properties);
        staticAssetStorageService.createStaticAssetStorageFromFile(file, staticAsset);
         ........
         .......

}

任何人都可以帮助我,为什么我在转换为多部分文件后得到零大小,我的方法是将图像文件转换为多部分文件?或者我需要遵循任何其他方法来实现此目的?

最佳答案

我建议使用此代码转换图像

FileInputStream input = new FileInputStream(fileItem);
MultipartFile multipartFile = new MockMultipartFile("fileItem",
            fileItem.getName(), "image/png", IOUtils.toByteArray(input));

如果你想使用 CommonsMultipartFile,我认为你应该在你的 pom 文件中添加 commons-fileupload

<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3</version> 
</dependency>

CommonsMultipartFile 的文档指出

NOTE: As of Spring 2.0, this class requires Commons FileUpload 1.1 or higher. The implementation does not use any deprecated FileUpload 1.0 API anymore, to be compatible with future Commons FileUpload releases. http://docs.spring.io/spring-framework/docs/2.0.8/api/org/springframework/web/multipart/commons/CommonsMultipartFile.html

请告诉我这是否适合您

关于java - 如何在 spring 中将图像转换为多部分文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38269876/

相关文章:

java - scan.hasNext 应该为真时为假

java - JBoss EAP6 - 无法创建 JDBC 数据源 (Microsoft SQL Server)

java - 如何阻止 SimpleMessageListenerContainer 陷入关闭/重新启动循环?

javascript - 如何使用 CSS3 和 Jquery 混合图像并按中心对齐它们?

html - 如何调整图像大小以始终适合所有屏幕尺寸(例如 Bootstrap 4)?

java - 将 memcached 与 Java 和 ScheduledFuture 对象结合使用

java - Guava:Iterables 转换方法的使用

java - 将 Spring 与 WebSphere 8.5.5 和 Apache Wink 结合使用 - 服务器启动时出现 web.xml 错误

Spring引导登录到多个文件

php - 使用PHP每秒更改网页中的图片