I created a file (below) but I want to convert it to MultipartFile, how can I do it?
I already tried this code, without sucess:
File file = new File("text.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
and that one result in a error:
File file = new File("text.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
Error
CommonsMultipartFile (org.apache.commons.fileupload.FileItem) in CommonsMultipartFile cannot be applied to (org.apache.tomcat.util.http.fileupload.disk.DiskFileItem)
Thanks
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;
}
In my case, works perfectly so, thank you Parthiban Manickam!!
InputStream stream = new FileInputStream(zipFile);
MockMultipartFile multipartFileToSend = new MockMultipartFile("file", zipFile.getName(),
String.valueOf(MediaType.MULTIPART_FORM_DATA), stream);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.