How to convert Image to multipart file in spring
I would suggest convert the image by using this code
FileInputStream input = new FileInputStream(fileItem);
MultipartFile multipartFile = new MockMultipartFile("fileItem",
fileItem.getName(), "image/png", IOUtils.toByteArray(input));
If you would like to use CommonsMultipartFile, I think you should have into your pom file the commons-fileupload
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
The documentation of CommonsMultipartFile states that
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
Let me know if this worked for you
Comments
-
subbu royal almost 2 years
I have an image file and creating
File
object with that imageFile file = new File("E://Shared Data/Images/xyz.jpg");
The above line is creating a
file
object with some size like440272
, I need to convert the aboveimage file
intomultipart file
for that I didDiskFileItem 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);
the problem is after converting I am getting
size=0
instead of getting somesize
like440272
. If I getsize
for theimage
so that I can store into some some location by passing it toupload
method.below is the upload method
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); ........ ....... }
can anyone help me why I am getting
zero size
after converting intomultipart file
is my approach is correct to convertimage file
tomultipart file
? or I need to follow any otherapproach
for this? -
subbu royal almost 8 years
MockMultipartFile
yeah it worked thank you very much.