Byte array to multipartfile java

Как преобразовать массив байтов в MultipartFile

Я получаю изображение в виде кодированной BASE64 String (encodedBytes) и использую следующий подход для декодирования в байте [] на стороне сервера.

BASE64Decoder decoder = new BASE64Decoder(); byte[] decodedBytes = decoder.decodeBuffer(encodedBytes); 

Теперь я хочу преобразовать его в MultipartFile, используя этот байт, полученный выше?

Есть ли способ конвертировать байт [] в org.springframework.web.multipart.MultipartFile??

ОТВЕТЫ

Ответ 1

org.springframework.web.multipart.MultipartFile — это интерфейс, поэтому сначала вам нужно будет поработать с реализацией этого интерфейса.

Единственная реализация, которую я могу видеть для этого интерфейса, который вы можете использовать «из коробки», это org.springframework.web.multipart.commons.CommonsMultipartFile . API для этой реализации можно найти здесь

В качестве альтернативы, поскольку org.springframework.web.multipart.MultipartFile является интерфейсом, вы можете предоставить собственную реализацию и просто обернуть свой байтовый массив. В качестве тривиального примера:

/* * 

* Trivial implementation of the interface to wrap a byte[] decoded * from a BASE64 encoded String *

*/ public class BASE64DecodedMultipartFile implements MultipartFile < private final byte[] imgContent; public BASE64DecodedMultipartFile(byte[] imgContent) < this.imgContent = imgContent; >@Override public String getName() < // TODO - implementation depends on your requirements return null; >@Override public String getOriginalFilename() < // TODO - implementation depends on your requirements return null; >@Override public String getContentType() < // TODO - implementation depends on your requirements return null; >@Override public boolean isEmpty() < return imgContent == null || imgContent.length == 0; >@Override public long getSize() < return imgContent.length; >@Override public byte[] getBytes() throws IOException < return imgContent; >@Override public InputStream getInputStream() throws IOException < return new ByteArrayInputStream(imgContent); >@Override public void transferTo(File dest) throws IOException, IllegalStateException < new FileOutputStream(dest).write(imgContent); >>

Ответ 2

Этот ответ уже ответил выше. Недавно я работал над требованием преобразовать объект массива байтов в объект multipartfile. Есть два способа добиться этого.

Читайте также:  nth-child

Используйте CommonsMultipartFile по умолчанию, где вы должны использовать объект FileDiskItem для его создания. Пример:

Используйте CommonsMultipartFile по умолчанию, где вы должны использовать объект FileDiskItem для его создания. Пример:

FileItem fileItem = new DiskFileItem("fileData", "application/pdf",true, outputFile.getName(), 100000000, new java.io.File(System.getProperty("java.io.tmpdir"))); MultipartFile multipartFile = new CommonsMultipartFile(fileItem); 

Создайте свой собственный многостраничный файловый объект и преобразуйте массив байтов в multipartfile.

public class CustomMultipartFile implements MultipartFile < private final byte[] fileContent; private String fileName; private String contentType; private File file; private String destPath = System.getProperty("java.io.tmpdir"); private FileOutputStream fileOutputStream; public CustomMultipartFile(byte[] fileData, String name) < this.fileContent = fileData; this.fileName = name; file = new File(destPath + fileName); >@Override public void transferTo(File dest) throws IOException, IllegalStateException < fileOutputStream = new FileOutputStream(dest); fileOutputStream.write(fileContent); >public void clearOutStreams() throws IOException < if (null != fileOutputStream) < fileOutputStream.flush(); fileOutputStream.close(); file.deleteOnExit(); >> @Override public byte[] getBytes() throws IOException < return fileContent; >@Override public InputStream getInputStream() throws IOException < return new ByteArrayInputStream(fileContent); >> 

Это, как вы можете использовать выше объекта CustomMultipartFile.

String fileName = "intermediate.pdf"; CustomMultipartFile customMultipartFile = new CustomMultipartFile(bytea, fileName); try < customMultipartFile.transferTo(customMultipartFile.getFile()); >catch (IllegalStateException e) < log.info("IllegalStateException : " + e); >catch (IOException e)

Это создаст необходимый PDF файл и сохранит его в

java.io.tmpdir с именем intermediate.pdf

Источник

Convert byte[] to MultipartFile in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll take a look at how to convert a byte array to MultipartFile.

MutlipartFile is an interface provided by Spring to receive files in multiple request chunks, so we need some implementation to instantiate a MultipartFile object. Spring does not provide any default implementation for code, but it does provide one for testing purposes.

2. Implementing MultipartFile Interface

Let’s create our own implementation for the MultipartFile interface and wrap the input byte array:

public class CustomMultipartFile implements MultipartFile < private byte[] input; @Override public String getName() < return null; >@Override public String getOriginalFilename() < return null; >@Override public String getContentType() < return null; >//We've defined the rest of the interface methods in the next snippet > 

We’ve defined a byte array attribute in our class so that we can capture the value for the input. Additionally, we’ve overridden the methods from the interface above, which depend on implementation detail. Therefore the details about the file name or content type can be provided as custom logic. As a result, we’ve returned null here.

We’ve also provided our own implementation for the other required methods from the interface:

public class CustomMultipartFile implements MultipartFile < //previous methods @Override public boolean isEmpty() < return input == null || input.length == 0; >@Override public long getSize() < return input.length; >@Override public byte[] getBytes() throws IOException < return input; >@Override public InputStream getInputStream() throws IOException < return new ByteArrayInputStream(input); >@Override public void transferTo(File destination) throws IOException, IllegalStateException < try(FileOutputStream fos = new FileOutputStream(destination)) < fos.write(input); >> >

These methods may not require any custom logic, so we’ve defined them in our class. There are several different ways to implement the transferTo(File destination) method. Let’s take a look at a few of them below:

@Override public void transferTo(File destination) throws IOException, IllegalStateException

Another option is adding the Apache commons IO dependency to our POM and using FileUtils class:

@Override public void transferTo(File destination) throws IOException, IllegalStateException

The transferTo(File destination) method is useful when the MultipartFile only needs to be written to a File, and there are several ways to write a MultipartFile to File.

Now that we’ve defined our class, let’s test this implementation with a small test case:

@Test void whenProvidingByteArray_thenMultipartFileCreated() throws IOException

We’ve successfully converted our byte array to a MultipartFile instance in the test case above.

3. MockMultipartFile

Spring provides MockMultipartFile out of the box for testing purposes to access Multipart requests.

Let’s create a test to see how it works:

@Test void whenProvidingByteArray_thenMockMultipartFileCreated() throws IOException

We’ve successfully used the Spring-provided MockMultipartFile object to convert the byte array into a MultipartFile Object.

4. Conclusion

In this tutorial, we covered how to convert a byte array into a MultipartFile object.

As usual, all code examples can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

San Song Daddy 🙂

Let’s assume you have a backend api and it accept MultipartFile as the request body. How can the client send a MultipartFile object in its body if client only has the bytes rather than a Resource?

implement MultipartFile interface

A representation of an uploaded file received in a multipart request.

The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at the end of request processing.

The below sample code implement a PDF MultipartFile.

public class PdfMultipartFile implements MultipartFile < private byte[] input; private String name; public PdfMultipartFile(byte[] input, String name) < this.input = input; this.name = name; >@Override public String getName() < return name; >@Override public String getOriginalFilename() < return name + ".pdf"; >@Override public String getContentType() < return MediaType.APPLICATION_PDF_VALUE; >@Override public boolean isEmpty() < return input == null || input.length == 0; >@Override public long getSize() < return input.length; >@Override public byte[] getBytes() throws IOException < return input; >@Override public InputStream getInputStream() throws IOException < return new ByteArrayInputStream(input); >@Override public void transferTo(File destination) throws IOException, IllegalStateException < try(FileOutputStream fos = new FileOutputStream(destination)) < fos.write(input); >> > 

MultipartFile.#transferTo(java.io.File)

Transfer the received file to the given destination file.

This may either move the file in the filesystem, copy the file in the filesystem, or save memory-held contents to the destination file. If the destination file already exists, it will be deleted first.

If the target file has been moved in the filesystem, this operation cannot be invoked again afterwards. Therefore, call this method just once in order to work with any storage mechanism.

NOTE: Depending on the underlying provider, temporary storage may be container-dependent, including the base directory for relative destinations specified here (e.g. with Servlet multipart handling). For absolute destinations, the target file may get renamed/moved from its temporary location or newly copied, even if a temporary copy already exists.

The good part with MultipartFile is you can verify the bytes your received or send out is the exactly file you want to transmit by transfer the bytes to a MultipartFile instance. with the help of MultipartFile::transferTo method, you can save the bytes into a file.

Источник

How to convert byte array to MultipartFile

w3toppers.com

org.springframework.web.multipart.MultipartFile is an interface so firstly you are going to need to work with an implementation of this interface.

The only implementation that I can see for that interface that you can use out-of-the-box is org.springframework.web.multipart.commons.CommonsMultipartFile . The API for that implementation can be found here

Alternatively as org.springframework.web.multipart.MultipartFile is an interface, you could provide your own implementation and simply wrap your byte array. As a trivial example:

/* * 

* Trivial implementation of the interface to wrap a byte[] decoded * from a BASE64 encoded String *

*/ public class BASE64DecodedMultipartFile implements MultipartFile < private final byte[] imgContent; public BASE64DecodedMultipartFile(byte[] imgContent) < this.imgContent = imgContent; >@Override public String getName() < // TODO - implementation depends on your requirements return null; >@Override public String getOriginalFilename() < // TODO - implementation depends on your requirements return null; >@Override public String getContentType() < // TODO - implementation depends on your requirements return null; >@Override public boolean isEmpty() < return imgContent == null || imgContent.length == 0; >@Override public long getSize() < return imgContent.length; >@Override public byte[] getBytes() throws IOException < return imgContent; >@Override public InputStream getInputStream() throws IOException < return new ByteArrayInputStream(imgContent); >@Override public void transferTo(File dest) throws IOException, IllegalStateException < new FileOutputStream(dest).write(imgContent); >>

Источник

Оцените статью