javafile-uploadstruts2java-iostruts2-interceptors

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:

@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?


Solution

  • 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:

    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

    File file = (File) uploadedFile.getContent();