Search in sources :

Example 6 with CommonsMultipartFile

use of org.springframework.web.multipart.commons.CommonsMultipartFile in project collect by openforis.

the class DataImportController method uploadData.

@RequestMapping(value = "/uploadData.htm", method = RequestMethod.POST)
@ResponseBody
public String uploadData(UploadItem uploadItem, BindingResult result, HttpServletRequest request, @RequestParam String sessionId) throws IOException, SurveyImportException {
    LOG.info("Uploading data file...");
    File file = File.createTempFile("collect_data_import", ".zip");
    LOG.info("Writing file: " + file.getAbsolutePath());
    // copy upload item to temp file
    CommonsMultipartFile fileData = uploadItem.getFileData();
    InputStream is = fileData.getInputStream();
    FileUtils.copyInputStreamToFile(is, file);
    LOG.info("Data file succeffully written");
    return file.getAbsolutePath();
}
Also used : InputStream(java.io.InputStream) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 7 with CommonsMultipartFile

use of org.springframework.web.multipart.commons.CommonsMultipartFile in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method uploadWithPath.

@ApiOperation(value = "Upload a file to a store with a path", notes = "Must have write access to the store")
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, value = "/{name}/**")
public ResponseEntity<List<FileModel>> uploadWithPath(@ApiParam(value = "Valid File Store name", required = true, allowMultiple = false) @PathVariable("name") String name, @AuthenticationPrincipal User user, @RequestParam(required = false, defaultValue = "false") boolean overwrite, MultipartHttpServletRequest multipartRequest, HttpServletRequest request) throws IOException {
    FileStoreDefinition def = ModuleRegistry.getFileStoreDefinition(name);
    if (def == null)
        throw new NotFoundRestException();
    // Check Permissions
    def.ensureStoreWritePermission(user);
    String pathInStore = parsePath(request);
    File root = def.getRoot().getCanonicalFile();
    Path rootPath = root.toPath();
    File outputDirectory = new File(root, pathInStore).getCanonicalFile();
    if (!outputDirectory.toPath().startsWith(rootPath)) {
        throw new GenericRestException(HttpStatus.FORBIDDEN, new TranslatableMessage("filestore.belowRoot", pathInStore));
    }
    if (outputDirectory.exists() && !outputDirectory.isDirectory()) {
        throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
    }
    if (!outputDirectory.exists()) {
        if (!outputDirectory.mkdirs())
            throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("filestore.cannotCreateDir", removeToRoot(root, outputDirectory), name));
    }
    // Put the file where it belongs
    List<FileModel> fileModels = new ArrayList<>();
    MultiValueMap<String, MultipartFile> filemap = multipartRequest.getMultiFileMap();
    for (String nameField : filemap.keySet()) {
        for (MultipartFile file : filemap.get(nameField)) {
            String filename;
            if (file instanceof CommonsMultipartFile) {
                FileItem fileItem = ((CommonsMultipartFile) file).getFileItem();
                filename = fileItem.getName();
            } else {
                filename = file.getName();
            }
            File newFile = findUniqueFileName(outputDirectory, filename, overwrite);
            File parent = newFile.getParentFile();
            if (!parent.exists()) {
                parent.mkdirs();
            }
            try (OutputStream output = new FileOutputStream(newFile, false)) {
                try (InputStream input = file.getInputStream()) {
                    StreamUtils.copy(input, output);
                }
            }
            fileModels.add(fileToModel(newFile, root, request.getServletContext()));
        }
    }
    return new ResponseEntity<>(fileModels, HttpStatus.OK);
}
Also used : Path(java.nio.file.Path) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) FileModel(com.infiniteautomation.mango.rest.v2.model.filestore.FileModel) FileItem(org.apache.commons.fileupload.FileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) FileOutputStream(java.io.FileOutputStream) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with CommonsMultipartFile

use of org.springframework.web.multipart.commons.CommonsMultipartFile in project molgenis by molgenis.

the class ImportWizardControllerTest method createMultipartFile.

private MultipartFile createMultipartFile(String filename) throws IOException {
    File file = new File("/src/test/resources/" + filename);
    DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length(), file.getParentFile());
    fileItem.getOutputStream();
    return new CommonsMultipartFile(fileItem);
}
Also used : File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile)

Example 9 with CommonsMultipartFile

use of org.springframework.web.multipart.commons.CommonsMultipartFile in project Asqatasun by Asqatasun.

the class UploadAuditSetUpCommandHelper method convertFilesToMap.

/**
 * This method converts the uploaded files into a map where the key is the
 * file name and the value is the file content.
 */
public static synchronized Map<String, String> convertFilesToMap(CommonsMultipartFile[] fileInputList) {
    Map<String, String> fileMap = new LinkedHashMap<String, String>();
    CommonsMultipartFile tmpMultiFile;
    String tmpCharset;
    fileNameCounterMap.clear();
    for (int i = 0; i < fileInputList.length; i++) {
        tmpMultiFile = fileInputList[i];
        try {
            if (tmpMultiFile != null && !tmpMultiFile.isEmpty() && tmpMultiFile.getInputStream() != null) {
                tmpCharset = HttpRequestHandler.extractCharset(tmpMultiFile.getInputStream());
                fileMap.put(getFileName(tmpMultiFile.getOriginalFilename()), tmpMultiFile.getFileItem().getString(tmpCharset));
            }
        } catch (IOException e) {
        }
    }
    return fileMap;
}
Also used : IOException(java.io.IOException) LinkedHashMap(java.util.LinkedHashMap) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile)

Example 10 with CommonsMultipartFile

use of org.springframework.web.multipart.commons.CommonsMultipartFile in project Asqatasun by Asqatasun.

the class UploadAuditSetUpFormValidator method validateFiles.

/**
 * Control whether the uploaded files are of HTML type and whether their
 * size is under the maxFileSize limit.
 *
 * @param uploadAuditSetUpCommand
 * @param errors
 */
private void validateFiles(AuditSetUpCommand uploadAuditSetUpCommand, Errors errors) {
    boolean emptyFile = true;
    Metadata metadata = new Metadata();
    MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository();
    String mime;
    for (int i = 0; i < uploadAuditSetUpCommand.getFileInputList().length; i++) {
        try {
            CommonsMultipartFile cmf = uploadAuditSetUpCommand.getFileInputList()[i];
            if (cmf.getSize() > maxFileSize) {
                Long maxFileSizeInMega = maxFileSize / 1000000;
                String[] arg = { maxFileSizeInMega.toString() };
                errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}");
            }
            if (cmf.getSize() > 0) {
                emptyFile = false;
                mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString();
                LOGGER.debug("mime  " + mime + "  " + cmf.getOriginalFilename());
                if (!authorizedMimeType.contains(mime)) {
                    errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
                }
            }
        } catch (IOException ex) {
            LOGGER.warn(ex.getMessage());
            errors.rejectValue(ID_INPUT_FILE_PREFIX + "[" + i + "]", NOT_HTML_MSG_BUNDLE_KEY);
        }
    }
    if (emptyFile) {
        // if no file is uploaded
        LOGGER.debug("emptyFiles");
        errors.rejectValue(GENERAL_ERROR_MSG_KEY, NO_FILE_UPLOADED_MSG_BUNDLE_KEY);
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) Metadata(org.apache.tika.metadata.Metadata) IOException(java.io.IOException) MimeTypes(org.apache.tika.mime.MimeTypes) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile)

Aggregations

CommonsMultipartFile (org.springframework.web.multipart.commons.CommonsMultipartFile)23 InputStream (java.io.InputStream)9 IOException (java.io.IOException)8 File (java.io.File)7 BaseTest (com.epam.ta.reportportal.BaseTest)5 Test (org.junit.jupiter.api.Test)5 MifosRuntimeException (org.mifos.core.MifosRuntimeException)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 MultipartFile (org.springframework.web.multipart.MultipartFile)4 FileItem (org.apache.commons.fileupload.FileItem)3 BufferedInputStream (java.io.BufferedInputStream)2 FileInputStream (java.io.FileInputStream)2 DiskFileItem (org.apache.commons.fileupload.disk.DiskFileItem)2 Metadata (org.apache.tika.metadata.Metadata)2 MimeTypes (org.apache.tika.mime.MimeTypes)2 LocalDate (org.joda.time.LocalDate)2 CreateAccountFeeDto (org.mifos.dto.domain.CreateAccountFeeDto)2 CreateAccountPenaltyDto (org.mifos.dto.domain.CreateAccountPenaltyDto)2 UploadedFileDto (org.mifos.dto.screen.UploadedFileDto)2 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)2