MockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
originalFileName, contentType, content);
Answer from Arun on Stack OverflowMockMultipartFile exists for this purpose. As in your snippet if the file path is known, the below code works for me.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.mock.web.MockMultipartFile;
Path path = Paths.get("/path/to/the/file.txt");
String name = "file.txt";
String originalFileName = "file.txt";
String contentType = "text/plain";
byte[] content = null;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
}
MultipartFile result = new MockMultipartFile(name,
originalFileName, contentType, content);
File file = new File("src/test/resources/input.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file",
file.getName(), "text/plain", IOUtils.toByteArray(input));
Hi!
I am trying to convert a string that is a URL from a PDF to a File, and then that file to a MultiPartFile.
This is the code I am using to create the MultiPartFile.
File file = new File(fileName);
try (final FileInputStream input = new FileInputStream(file)) {
multipartFile = new MockMultipartFile(
fileName,
file.getName(),
String.valueOf(MediaType.APPLICATION_PDF),
IOUtils.toByteArray(input));
}
This seems to generate the MultiPartFile fine, but then it uploads to a bucket in s3, and when I try to open it I can't, it just says it can't be opened. But idk if this is a problem when generating the MultiPartFile or uploading it to s3. It doesn't break when generating it or uploading it, only when I try to open it from aws, it tries to load but it says "We cant open this file".
Does anyone know what I could be doing wrong, or what I could try? Thank you very much!
java - How to convert a multipart file to File? - Stack Overflow
java - Converting File to MultiPartFile with spring - Stack Overflow
Java spring: best way to convert a File to a MultipartFile - Stack Overflow
How to create a Multipart file using java - Stack Overflow
Videos
You can get the content of a MultipartFile by using the getBytes method and you can write to the file using Files.newOutputStream():
public void write(MultipartFile file, Path dir) {
Path filepath = Paths.get(dir.toString(), file.getOriginalFilename());
try (OutputStream os = Files.newOutputStream(filepath)) {
os.write(file.getBytes());
}
}
You can also use the transferTo method:
public void multipartFileToFile(
MultipartFile multipart,
Path dir
) throws IOException {
Path filepath = Paths.get(dir.toString(), multipart.getOriginalFilename());
multipart.transferTo(filepath);
}
small correction on @PetrosTsialiamanis post ,
new File( multipart.getOriginalFilename()) this will create file in server location where sometime you will face write permission issues for the user, its not always possible to give write permission to every user who perform action.
System.getProperty("java.io.tmpdir") will create temp directory where your file will be created properly.
This way you are creating temp folder, where file gets created , later on you can delete file or temp folder.
public static File multipartToFile(MultipartFile multipart, String fileName) throws IllegalStateException, IOException {
File convFile = new File(System.getProperty("java.io.tmpdir")+"/"+fileName);
multipart.transferTo(convFile);
return convFile;
}
put this method in ur common utility and use it like for eg. Utility.multipartToFile(...)
File file = new File("src/test/resources/input.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file",
file.getName(), "text/plain", IOUtils.toByteArray(input));
This is another way of getting multipart file from File object
File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
You need the
fileItem.getOutputStream();
because it will throw NPE otherwise.
InputStream stream = new FileInputStream(file)
multipartFileToSend = new MockMultipartFile("file", file.getName(), MediaType.TEXT_HTML_VALUE, stream);
try this
I propose this method which allows converting a File to a MultipartFile:
public static MultipartFile buildMultipartFile(@NonNull final File file,
@NonNull final String multipartFileParameterName) throws IOException {
MultipartFile multipartFile = null;
try (final FileInputStream input = new FileInputStream(file)) {
multipartFile = new MockMultipartFile(
multipartFileParameterName,
file.getName(),
Files.probeContentType(file.toPath()),
IOUtils.toByteArray(input));
}
return multipartFile;
}
If you upload like that then file will read from local and it will not read when u check-in or run from server.
Use common Multipart or standard Multipart resolver which may solve your issue.
Refer below code.
JSP
method="POST" enctype="multipart/form-data">
Controller:
Multipart upload;
byte[] bytes = file.getBytes();
Path path=file.get(fileinputstream (upload));
Bean:
private Multipart upload;
Getter and setter method;
Register Bean
@Bean public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
You can create Multipart file using MockMultipartFile in java.
MultipartFile multipartFile = new MockMultipartFile("sourceFile.tmp", "Hello World".getBytes());
private MultipartFile getResize(MultipartFile orginalFile, int h, int w) throws IOException {
File convFile = new File(orginalFile.getOriginalFilename());
BufferedImage bImage = ImageIO.read(convFile);
Image tmp = bImage.getScaledInstance(w, h, Image.SCALE_SMOOTH);
BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = resized.createGraphics();
g2d.drawImage(tmp, 0, 0, null);
g2d.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(resized, โpngโ, os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
byte[] buffer = new byte[is.available()];I am not able to figure out to return the multipartfile conversion for this image resize.