How to convert uploadedFile to file without giving path in struts2 spring

I need to use ActionUploadFileInterceptor. I implement UploadedFilesAware and need to convert UploadedFile to File. I write a method for convertUploadedFileToFile.

Is there any better way to convert uploadFile to a File in Struts?

Is it correct convertUploadedFileToFile()?
What is type of uploadedFile.getContent()?
Here is my code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>@ConversationController
public class SampleAction extends BaseActionSupport implements UploadedFilesAware {
private List<UploadedFile> uploadedFiles;
public String upload() {
if (uploadedFiles != null && !uploadedFiles.isEmpty()) {
for (UploadedFile file : uploadedFiles) {
String fileName = file.getOriginalName(); // Get the file name
LOG.debug("uploading file for OwnToOther Batch {}", fileName);
String ext = FilenameUtils.getExtension(fileName);
if (ext.equalsIgnoreCase("xlsx") || ext.equalsIgnoreCase("xls")) {
processExcelFile(file);
} else {
processCSVFile(file);
}
}
}
setGridModel(transferVOList.getFundTransferList());
return SUCCESS;
}
private void processExcelFile(UploadedFile uploadedFile) {
List<List<String>> dataEntriesList;
List<FundTransferVO> transVOList;
try {
File file = convertUploadedFileToFile(uploadedFile);
dataEntriesList = excelReader.read(file, COLUMN_NUMBER);
transVOList = excelReader.populateBeans(dataEntriesList);
// ...
} catch (IOException ex) {
LOG.error("Error in reading the uploaded excel file: ", ex);
} catch (InvalidFormatException ex) {
LOG.error("File format error while reading the uploaded excel file:", ex);
}
}
private File convertUploadedFileToFile(UploadedFile uploadedFile) throws IOException {
File file = new File(uploadedFile.getOriginalName());
Object contentObject = uploadedFile.getContent();
if (contentObject instanceof InputStream) {
try (InputStream inputStream = (InputStream) contentObject;
FileOutputStream outputStream = new FileOutputStream(file)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
} else if (contentObject instanceof byte[]) {
byte[] content = (byte[]) contentObject;
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(content);
}
} else if (contentObject instanceof String) {
String content = (String) contentObject;
try (FileOutputStream outputStream = new FileOutputStream(file)) {
outputStream.write(content.getBytes());
}
} else if (contentObject instanceof File) {
File contentFile = (File) contentObject;
Files.copy(contentFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
} else {
throw new IOException("Unsupported content type: " + contentObject.getClass().getName());
}
return file;
}
@Override
public void withUploadedFiles(List<UploadedFile> uploadedFiles) {
this.uploadedFiles = uploadedFiles;
}
}
</code>
<code>@ConversationController public class SampleAction extends BaseActionSupport implements UploadedFilesAware { private List<UploadedFile> uploadedFiles; public String upload() { if (uploadedFiles != null && !uploadedFiles.isEmpty()) { for (UploadedFile file : uploadedFiles) { String fileName = file.getOriginalName(); // Get the file name LOG.debug("uploading file for OwnToOther Batch {}", fileName); String ext = FilenameUtils.getExtension(fileName); if (ext.equalsIgnoreCase("xlsx") || ext.equalsIgnoreCase("xls")) { processExcelFile(file); } else { processCSVFile(file); } } } setGridModel(transferVOList.getFundTransferList()); return SUCCESS; } private void processExcelFile(UploadedFile uploadedFile) { List<List<String>> dataEntriesList; List<FundTransferVO> transVOList; try { File file = convertUploadedFileToFile(uploadedFile); dataEntriesList = excelReader.read(file, COLUMN_NUMBER); transVOList = excelReader.populateBeans(dataEntriesList); // ... } catch (IOException ex) { LOG.error("Error in reading the uploaded excel file: ", ex); } catch (InvalidFormatException ex) { LOG.error("File format error while reading the uploaded excel file:", ex); } } private File convertUploadedFileToFile(UploadedFile uploadedFile) throws IOException { File file = new File(uploadedFile.getOriginalName()); Object contentObject = uploadedFile.getContent(); if (contentObject instanceof InputStream) { try (InputStream inputStream = (InputStream) contentObject; FileOutputStream outputStream = new FileOutputStream(file)) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } } else if (contentObject instanceof byte[]) { byte[] content = (byte[]) contentObject; try (FileOutputStream outputStream = new FileOutputStream(file)) { outputStream.write(content); } } else if (contentObject instanceof String) { String content = (String) contentObject; try (FileOutputStream outputStream = new FileOutputStream(file)) { outputStream.write(content.getBytes()); } } else if (contentObject instanceof File) { File contentFile = (File) contentObject; Files.copy(contentFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); } else { throw new IOException("Unsupported content type: " + contentObject.getClass().getName()); } return file; } @Override public void withUploadedFiles(List<UploadedFile> uploadedFiles) { this.uploadedFiles = uploadedFiles; } } </code>
@ConversationController
public class SampleAction extends BaseActionSupport implements UploadedFilesAware {

    private List<UploadedFile> uploadedFiles;
    public String upload() {
        if (uploadedFiles != null && !uploadedFiles.isEmpty()) {
            for (UploadedFile file : uploadedFiles) {
                String fileName = file.getOriginalName(); // Get the file name
                LOG.debug("uploading file for OwnToOther Batch {}", fileName);
                String ext = FilenameUtils.getExtension(fileName);
                if (ext.equalsIgnoreCase("xlsx") || ext.equalsIgnoreCase("xls")) {
                    processExcelFile(file);
                } else {
                    processCSVFile(file);
                }
            }
        }
        setGridModel(transferVOList.getFundTransferList());

        return SUCCESS;
    }

    private void processExcelFile(UploadedFile uploadedFile) {

        List<List<String>> dataEntriesList;
        List<FundTransferVO> transVOList;
        try {
            File file = convertUploadedFileToFile(uploadedFile);
            dataEntriesList = excelReader.read(file, COLUMN_NUMBER);
            transVOList = excelReader.populateBeans(dataEntriesList);
            // ...

        } catch (IOException ex) {
            LOG.error("Error in reading the uploaded excel file: ", ex);
        } catch (InvalidFormatException ex) {
            LOG.error("File format error while reading the uploaded excel file:", ex);
        }
    }

    private File convertUploadedFileToFile(UploadedFile uploadedFile) throws IOException {
        File file = new File(uploadedFile.getOriginalName());
        Object contentObject = uploadedFile.getContent();
        if (contentObject instanceof InputStream) {
            try (InputStream inputStream = (InputStream) contentObject;
                    FileOutputStream outputStream = new FileOutputStream(file)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        } else if (contentObject instanceof byte[]) {
            byte[] content = (byte[]) contentObject;
            try (FileOutputStream outputStream = new FileOutputStream(file)) {
                outputStream.write(content);
            }
        } else if (contentObject instanceof String) {
            String content = (String) contentObject;
            try (FileOutputStream outputStream = new FileOutputStream(file)) {
                outputStream.write(content.getBytes());
            }
        } else if (contentObject instanceof File) {
            File contentFile = (File) contentObject;
            Files.copy(contentFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } else {
            throw new IOException("Unsupported content type: " + contentObject.getClass().getName());
        }

        return file;
    }
    @Override
    public void withUploadedFiles(List<UploadedFile> uploadedFiles) {
        this.uploadedFiles = uploadedFiles;
    }
}

Is there any better way to convert uploadFile to a File in Struts?

5

If you need to use actionFileUpload interceptor then you should read Action File Upload Interceptor.

Interceptor that is based off of MultiPartRequestWrapper, which is automatically applied for any request that includes a file. If an action implements org.apache.struts2.action.UploadedFilesAware interface, the interceptor will pass information and content of uploaded files using the callback method withUploadedFiles(List<UploadedFile>).

See examples page.

If you use by default configuration in application.properties:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>struts.multipart.parser=jakarta
</code>
<code>struts.multipart.parser=jakarta </code>
struts.multipart.parser=jakarta

then you don’t need to convert UploadedFile::getContent to File. If you don’t use custom parser then just cast it directly. Only StrutsUploadedFile inplemented UploadedFile and it returns File type

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>File file = (File) uploadedFile.getContent();
</code>
<code>File file = (File) uploadedFile.getContent(); </code>
File file = (File) uploadedFile.getContent();

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật