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();
}
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);
}
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);
}
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;
}
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);
}
}
Aggregations