List of usage examples for org.springframework.web.multipart MultipartFile transferTo
default void transferTo(Path dest) throws IOException, IllegalStateException
From source file:org.cloudifysource.rest.repo.UploadRepo.java
private void copyMultipartFileToLocalFile(final MultipartFile srcFile, final File storedFile) throws IOException { if (srcFile == null) { return;// w w w .j av a 2 s . co m } srcFile.transferTo(storedFile); storedFile.deleteOnExit(); }
From source file:org.davidmendoza.fileUpload.web.ImageController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) { log.debug("uploadPost called"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<Image> list = new LinkedList<>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); log.debug("Uploading {}", mpf.getOriginalFilename()); String newFilenameBase = UUID.randomUUID().toString(); String originalFileExtension = mpf.getOriginalFilename() .substring(mpf.getOriginalFilename().lastIndexOf(".")); String newFilename = newFilenameBase + originalFileExtension; String storageDirectory = fileUploadDirectory; String contentType = mpf.getContentType(); File newFile = new File(storageDirectory + "/" + newFilename); try {// w w w. j a v a2 s . com mpf.transferTo(newFile); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); String thumbnailFilename = newFilenameBase + "-thumbnail.png"; File thumbnailFile = new File(storageDirectory + "/" + thumbnailFilename); ImageIO.write(thumbnail, "png", thumbnailFile); Image image = new Image(); image.setName(mpf.getOriginalFilename()); image.setThumbnailFilename(thumbnailFilename); image.setNewFilename(newFilename); image.setContentType(contentType); image.setSize(mpf.getSize()); image.setThumbnailSize(thumbnailFile.length()); image = imageDao.create(image); image.setUrl("/picture/" + image.getId()); image.setThumbnailUrl("/thumbnail/" + image.getId()); image.setDeleteUrl("/delete/" + image.getId()); image.setDeleteType("DELETE"); list.add(image); } catch (IOException e) { log.error("Could not upload file " + mpf.getOriginalFilename(), e); } } Map<String, Object> files = new HashMap<>(); files.put("files", list); return files; }
From source file:org.esupportail.publisher.service.FileService.java
private String uploadResource(final Long entityId, final String name, final MultipartFile file, final FileUploadHelper fileUploadHelper) throws MultipartException { // Checking size if (file.getSize() > fileUploadHelper.getFileMaxSize()) { throw new MaxUploadSizeExceededException(fileUploadHelper.getFileMaxSize()); }// w w w.j av a2 s.c o m // Checking ContentType Pair<Boolean, MultipartException> isAuthorized = isAuthorizedMimeType(file, fileUploadHelper); Assert.notNull(isAuthorized.getFirst()); if (!isAuthorized.getFirst()) { if (isAuthorized.getSecond() != null) throw isAuthorized.getSecond(); return null; } try { final String fileExt = Files.getFileExtension(file.getOriginalFilename()).toLowerCase(); String fname = new SimpleDateFormat("yyyyMMddHHmmss'." + fileExt + "'").format(new Date()); // if (name != null && name.length() > 0 ) { // fname = Files.getNameWithoutExtension(name) + "-" + fname; // } final String internPath = fileUploadHelper.getUploadDirectoryPath(); final String relativPath = String.valueOf(entityId).hashCode() + File.separator + df.format(new Date()) + File.separator; final String path = internPath + relativPath; File inFile = new File(path + fname); // checking if path is existing if (!inFile.getParentFile().exists()) { boolean error = !inFile.getParentFile().mkdirs(); if (error) { log.error("Can't create directory {} to upload file, track error!", inFile.getParentFile().getPath()); return null; } } // checking if file exist else renaming file name int i = 1; while (inFile.exists()) { inFile = new File(path + i + fname); i++; } log.debug("Uploading file as {}", inFile.getPath()); // start upload file.transferTo(inFile); return fileUploadHelper.getUrlResourceMapping() + relativPath + fname; } catch (Exception e) { log.error("File Upload error", e); return null; } }
From source file:org.fao.geonet.api.registries.DirectoryApi.java
private File[] unzipAndFilterShp(MultipartFile file) throws IOException, URISyntaxException { Path toDirectory = Files.createTempDirectory("gn-imported-entries-"); toDirectory.toFile().deleteOnExit(); File zipFile = new File(Paths.get(toDirectory.toString(), file.getOriginalFilename()).toString()); ;// w w w. j a v a 2 s .c o m file.transferTo(zipFile); ZipUtil.extract(zipFile.toPath(), toDirectory); File[] shapefiles = toDirectory.toFile().listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".shp"); } }); return shapefiles; }
From source file:org.fao.geonet.api.registries.vocabularies.KeywordsApi.java
/** * Upload thesaurus.// w ww .j av a2 s . c om * * @param file the file * @param type the type * @param dir the dir * @param stylesheet the stylesheet * @param request the request * @return the element * @throws Exception the exception */ @ApiOperation(value = "Uploads a new thesaurus from a file", nickname = "uploadThesaurus", notes = "Uploads a new thesaurus.") @RequestMapping(method = RequestMethod.POST, produces = MediaType.TEXT_XML_VALUE) @ApiResponses(value = { @ApiResponse(code = 201, message = "Thesaurus uploaded in SKOS format."), @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_REVIEWER) }) @PreAuthorize("hasRole('Reviewer')") @ResponseBody @ResponseStatus(value = HttpStatus.CREATED) public String uploadThesaurus( @ApiParam(value = "If set, do a file upload.") @RequestParam(value = "file", required = false) MultipartFile file, @ApiParam(value = "Local or external (default).") @RequestParam(value = "type", defaultValue = "external") String type, @ApiParam(value = "Type of thesaurus, usually one of the ISO thesaurus type codelist value. Default is theme.") @RequestParam(value = "dir", defaultValue = "theme") String dir, @ApiParam(value = "XSL to be use to convert the thesaurus before load. Default _none_.") @RequestParam(value = "stylesheet", defaultValue = "_none_") String stylesheet, HttpServletRequest request) throws Exception { long start = System.currentTimeMillis(); ServiceContext context = ApiUtils.createServiceContext(request); // Different options for upload boolean fileUpload = file != null && !file.isEmpty(); // Upload RDF file Path rdfFile = null; String fname = null; File tempDir = null; if (fileUpload) { Log.debug(Geonet.THESAURUS, "Uploading thesaurus file: " + file.getOriginalFilename()); tempDir = Files.createTempDirectory("thesaurus").toFile(); Path tempFilePath = tempDir.toPath().resolve(file.getOriginalFilename()); File convFile = tempFilePath.toFile(); file.transferTo(convFile); rdfFile = convFile.toPath(); fname = file.getOriginalFilename(); } else { Log.debug(Geonet.THESAURUS, "No file provided for thesaurus upload."); throw new MissingServletRequestParameterException("Thesaurus source not provided", "file"); } try { if (StringUtils.isEmpty(fname)) { throw new Exception("File upload from URL or file return null"); } long fsize; if (rdfFile != null && Files.exists(rdfFile)) { fsize = Files.size(rdfFile); } else { throw new MissingServletRequestParameterException("Thesaurus file doesn't exist", "file"); } // -- check that the archive actually has something in it if (fsize == 0) { throw new MissingServletRequestParameterException("Thesaurus file has zero size", "file"); } String extension = FilenameUtils.getExtension(fname); if (extension.equalsIgnoreCase("rdf") || extension.equalsIgnoreCase("xml")) { Log.debug(Geonet.THESAURUS, "Uploading thesaurus: " + fname); // Rename .xml to .rdf for all thesaurus fname = fname.replace(extension, "rdf"); uploadThesaurus(rdfFile, stylesheet, context, fname, type, dir); } else { Log.debug(Geonet.THESAURUS, "Incorrect extension for thesaurus named: " + fname); throw new Exception("Incorrect extension for thesaurus named: " + fname); } long end = System.currentTimeMillis(); long duration = (end - start) / 1000; return String.format("Thesaurus '%s' loaded in %d sec.", fname, duration); } finally { if (tempDir != null) { FileUtils.deleteQuietly(tempDir); } } }
From source file:org.openlegacy.mvc.AbstractRestController.java
protected void uploadImage(MultipartFile file, HttpServletResponse response) throws IOException { String fileName = file.getOriginalFilename(); fileName = fileName.replaceAll(" ", "_"); if (uploadDir == null) { String property = "java.io.tmpdir"; // Get the temporary directory and print it. uploadDir = System.getProperty(property); }/*from w ww . ja v a 2 s . c o m*/ file.transferTo(new File(uploadDir, fileName)); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print("{\"filename\":\"" + fileName + "\"}"); out.flush(); }
From source file:org.opentestsystem.authoring.testitembank.rest.ImportSetController.java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody//from w w w .j a v a2 s. c om @Secured({ "ROLE_Tib Import" }) public ImportSet importUploadFile(@RequestParam("file") final MultipartFile apipFile, @RequestParam(required = true) final String tenantId, @RequestParam(required = true) final String itemBank, final HttpServletResponse response) { String path = tempFileDirectory; if (StringUtils.isEmpty(tempFileDirectory)) { final String userDir = System.getProperty("user.dir"); LOGGER.info("The property 'tib.file.pathname' is not populated, defaulting to :" + userDir); path = userDir; } final String fileName = System.currentTimeMillis() + "_" + apipFile.getOriginalFilename(); LOGGER.debug("TIB temp dir is: " + path + " file name: " + fileName); final File file = new File(path, fileName); ImportSet savedImportSet = null; final ImportSet importSet = new ImportSet(); try { apipFile.transferTo(file); importSet.setTenantId(tenantId); importSet.setItemBank(itemBank); importSet.setImportType(ImportType.MULTIPART_REQUEST); importSet.setImportStatus(ImportStatus.UNIMPORTED); importSet.setRequestTime(new DateTime()); if (file.exists()) { importSet.addFileToImport(file); savedImportSet = importSetService.saveImportSet(importSet); importSetService.importFileSet(importSet); savedImportSet = importSetService.getImportSet(importSet.getId()); } else { importSet.setImportStatus(ImportStatus.FILE_NOT_FOUND); savedImportSet = importSetService.saveImportSet(importSet); } if (ImportStatus.IMPORT_COMPLETE.equals(importSet.getImportStatus())) { response.setStatus(HttpStatus.CREATED.value()); response.setHeader("Location", savedImportSet.getUrl()); } else { response.setStatus(HttpStatus.BAD_REQUEST.value()); } } catch (final Exception e) { importSet.setImportStatus(ImportStatus.FAILED); savedImportSet = importSetService.saveImportSet(importSet); response.setStatus(HttpStatus.BAD_REQUEST.value()); throw new RestException("upload.error", e); } finally { if (file != null) { try { file.delete(); } catch (final Exception e) { throw new TestItemBankException("unexpected.error", e); } } } return savedImportSet; }
From source file:org.sakaiproject.assignment2.tool.beans.UploadBean.java
private WorkFlowResult processUploadAll(MultipartFile uploadedFile, Assignment2 assign) { if (!AssignmentAuthoringBean.checkCsrf(csrfToken)) return WorkFlowResult.UPLOAD_FAILURE; // you should have already done validation on the file at this point File newFile = null;/*from ww w. jav a2 s . c o m*/ try { newFile = File.createTempFile(uploadedFile.getName(), ".zip"); uploadedFile.transferTo(newFile); } catch (IOException ioe) { if (newFile != null) { newFile.delete(); } throw new UploadException(ioe.getMessage(), ioe); } // try to upload this file try { List<Map<String, String>> uploadInfo = uploadAllLogic.uploadAll(uploadOptions, newFile); addUploadMessages(uploadInfo); } catch (UploadException ue) { if (log.isDebugEnabled()) log.debug("UploadException encountered while attempting to UploadAll for assignment: " + assign.getTitle(), ue); messages.addMessage(new TargettedMessage("assignment2.uploadall.error.failure", new Object[] { assign.getTitle() })); return WorkFlowResult.UPLOAD_FAILURE; } finally { if (newFile != null) { newFile.delete(); } } // ASNN-29 This is the end and it uploads all the grades here for zip triggerUploadEvent(assign); return WorkFlowResult.UPLOAD_SUCCESS; }
From source file:org.sakaiproject.assignment2.tool.beans.UploadBean.java
/** * Action Method Binding for the Upload Button on the initial page of the * upload workflow/wizard.//from w ww .j ava 2 s . c o m * * @return */ private WorkFlowResult processUploadGradesCSV(MultipartFile uploadedFile, Assignment2 assignment) { if (!AssignmentAuthoringBean.checkCsrf(csrfToken)) return WorkFlowResult.UPLOAD_FAILURE; // validation on file should have already occurred File newFile = null; try { newFile = File.createTempFile(uploadedFile.getName(), ".csv"); uploadedFile.transferTo(newFile); } catch (IOException ioe) { throw new UploadException(ioe.getMessage(), ioe); } // retrieve the displayIdUserId info once and re-use it Set<String> submitters = permissionLogic.getSubmittersInSite(assignment.getContextId()); displayIdUserIdMap = externalLogic.getUserDisplayIdUserIdMapForUsers(submitters); parsedContent = uploadGradesLogic.getCSVContent(newFile); // delete the file newFile.delete(); // ensure that there is not an unreasonable number of rows compared to // the number of students in the site int numStudentsInSite = displayIdUserIdMap.size(); int numRowsInUpload = parsedContent.size(); if (numRowsInUpload > (numStudentsInSite + 50)) { messages.addMessage(new TargettedMessage("assignment2.upload_grades.too_many_rows", new Object[] { numRowsInUpload, numStudentsInSite }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOADALL_CSV_UPLOAD_FAILURE; } // let's check that the students included in the file are actually in the site List<String> invalidDisplayIds = uploadGradesLogic.getInvalidDisplayIdsInContent(displayIdUserIdMap, parsedContent); if (invalidDisplayIds != null && !invalidDisplayIds.isEmpty()) { messages.addMessage(new TargettedMessage("assignment2.upload_grades.user_not_in_site", new Object[] { getListAsString(invalidDisplayIds) }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOADALL_CSV_UPLOAD_FAILURE; } // check that the grades are valid List<String> displayIdsWithInvalidGrade = uploadGradesLogic .getStudentsWithInvalidGradesInContent(parsedContent, assignment.getContextId()); if (displayIdsWithInvalidGrade != null && !displayIdsWithInvalidGrade.isEmpty()) { messages.addMessage(new TargettedMessage("assignment2.upload_grades.grades_not_valid", new Object[] { getListAsString(displayIdsWithInvalidGrade) }, TargettedMessage.SEVERITY_ERROR)); return WorkFlowResult.UPLOADALL_CSV_UPLOAD_FAILURE; } // let's proceed with the grade upload return WorkFlowResult.UPLOADALL_CSV_UPLOAD; }
From source file:org.springframework.batch.admin.web.BatchFileController.java
@RequestMapping(value = "/{path}", method = RequestMethod.POST) public String upload(@PathVariable String path, @RequestParam MultipartFile file, ModelMap model, @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize, @ModelAttribute("date") Date date, Errors errors) throws Exception { String originalFilename = file.getOriginalFilename(); if (file.isEmpty()) { errors.reject("file.upload.empty", new Object[] { originalFilename }, "File upload was empty for filename=[" + HtmlUtils.htmlEscape(originalFilename) + "]"); return null; }/* w ww . j ava2 s. com*/ try { FileInfo dest = fileService.createFile(path + "/" + originalFilename); file.transferTo(fileService.getResource(dest.getPath()).getFile()); fileService.publish(dest); model.put("uploaded", dest.getPath()); } catch (IOException e) { errors.reject("file.upload.failed", new Object[] { originalFilename }, "File upload failed for " + HtmlUtils.htmlEscape(originalFilename)); } catch (Exception e) { String message = "File upload failed downstream processing for " + HtmlUtils.htmlEscape(originalFilename); if (logger.isDebugEnabled()) { logger.debug(message, e); } else { logger.info(message); } errors.reject("file.upload.failed.downstream", new Object[] { originalFilename }, message); } return null; }