List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:org.trpr.platform.batch.impl.spring.web.JobConfigController.java
/** * This method handles all the configuration changes: * Uploading of XML File//from w w w . j a v a2 s.c o m * Uploading of dependency * Saving the changes in XML File */ @RequestMapping(value = "configuration/modify/jobs/{jobName}", method = RequestMethod.POST) public String editJob(ModelMap model, @RequestParam(value = "jobName") String[] jobNames, @RequestParam(defaultValue = "") String XMLFileContents, @RequestParam(defaultValue = "0") MultipartFile jobFile, @RequestParam(defaultValue = "0") MultipartFile depFile, @RequestParam(defaultValue = "0") String identifier) throws Exception { List<String> jobNameList = Arrays.asList(jobNames); //FOr getter methods, such as getJobdependency, any of the jobNames among the list would do String jobName = jobNameList.get(0); //Button 1: Upload XML if (identifier.equals("Upload file")) { String jobFileName = jobFile.getOriginalFilename(); //Check if file is empty or doesn't have an extension if (jobFile.isEmpty() || (jobFileName.lastIndexOf('.') < 0)) { model.addAttribute("XMLFileError", "File is Empty or invalid. Only .xml files can be uploaded"); } else if (!jobFileName.substring(jobFileName.lastIndexOf('.')).equals(".xml")) {//Check if file is .xml model.addAttribute("XMLFileError", "Only .xml files can be uploaded"); } else { //Read file to view byte[] buffer = jobFile.getBytes(); XMLFileContents = new String(buffer); model.addAttribute("XMLFileContents", XMLFileContents); } } else if (identifier.equals("Upload dependency")) { //Button 2: Upload dependencies String depFileName = depFile.getOriginalFilename(); if (depFile.isEmpty() || (depFileName.lastIndexOf('.') < 0)) { model.addAttribute("DepFileError", "File is Empty or invalid. Only .jar files can be uploaded"); } else if (!depFileName.substring(depFileName.lastIndexOf('.')).equals(".jar")) { //Check if file is valid model.addAttribute("DepFileError", "Only .jar files can be uploaded"); } else {//Move uploaded file //Check if file hasn't been added already if (jobConfigService.getJobDependencyList(jobName) != null && jobConfigService.getJobDependencyList(jobName).contains(depFileName)) { model.addAttribute("DepFileError", "The filename is already added. Overwriting"); } jobConfigService.addJobDependency(jobNameList, depFile.getOriginalFilename(), depFile.getBytes()); } } else { //Button 3: Save. Overwrite the modified XML File LOGGER.info("Request to deploy jobConfig file for: " + jobNameList); try { //Set XML File this.jobConfigService.setJobConfig(jobNameList, new ByteArrayResource(XMLFileContents.getBytes())); this.jobConfigService.deployJob(jobNameList); } catch (Exception e) { LOGGER.info("Error while deploying job", e); //View: Add Error and rest of the attributes //Get stacktrace as string StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); model.addAttribute("LoadingError", errors.toString()); if (errors.toString() == null) { model.addAttribute("LoadingError", "Unexpected error"); } model.addAttribute("XMLFileContents", XMLFileContents.trim()); model.addAttribute("jobName", jobNameList); if (jobConfigService.getJobDependencyList(jobName) != null) { model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName)); } model.addAttribute("XMLFileContents", XMLFileContents.trim()); //Redirect return "configuration/modify/jobs/job"; } //Loading worked. Deploy to all hosts if (this.jobConfigService.getSyncService() != null) this.jobConfigService.getSyncService().deployJobToAllHosts(jobName); //Redirect to job configuration page. Load the view details model.addAttribute("SuccessMessage", "The job was successfully deployed!"); model.addAttribute("jobName", jobName); //Push jobs to all servers if (jobConfigService.getJobDependencyList(jobName) != null) { model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName)); } model.addAttribute("XMLFileContents", XMLFileContents.trim()); String jobDirectory = this.jobConfigService.getJobStoreURI(jobName).getPath(); model.addAttribute("JobDirectoryName", jobDirectory.substring(jobDirectory.lastIndexOf('/') + 1) + "/lib"); return "configuration/jobs/job"; } //Update the view model.addAttribute("jobName", jobNameList); if (jobConfigService.getJobDependencyList(jobName) != null) { model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName)); } model.addAttribute("XMLFileContents", XMLFileContents); //Redirect to modify page return "configuration/modify/jobs/job"; }
From source file:it.cilea.osd.jdyna.web.controller.ImportAnagraficaObject.java
/** Performa l'import da file xml di configurazioni di oggetti; * Sull'upload del file la configurazione dell'oggetto viene caricato come contesto di spring * e salvate su db./* w w w. jav a2s.c o m*/ */ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object, BindException errors) throws RuntimeException, IOException { FileUploadConfiguration bean = (FileUploadConfiguration) object; MultipartFile file = (CommonsMultipartFile) bean.getFile(); File a = null; //creo il file temporaneo che sara' caricato come contesto di spring per caricare la configurazione degli oggetti a = File.createTempFile("jdyna", ".xml", new File(path)); file.transferTo(a); ApplicationContext context = null; try { context = new FileSystemXmlApplicationContext(new String[] { "file:" + a.getAbsolutePath() }); } catch (XmlBeanDefinitionStoreException exc) { //cancello il file dalla directory temporanea logger.warn("Error during the configuration import from file: " + file.getOriginalFilename(), exc); a.delete(); saveMessage(request, getText("action.file.nosuccess.upload", new Object[] { exc.getMessage() }, request.getLocale())); return new ModelAndView(getErrorView()); } //cancello il file dalla directory temporanea a.delete(); String[] tpDefinitions = context.getBeanDefinitionNames(); //getBeanNamesForType(tpClass); AnagraficaObject<P, TP> anagraficaObject = null; String idStringAnagraficaObject = request.getParameter("id"); Integer pkey = Integer.parseInt(idStringAnagraficaObject); anagraficaObject = applicationService.get(modelClass, pkey); //la variabile i conta le tipologie caricate con successo int i = 0; //la variabile j conta le tipologie non caricate int j = 0; for (String tpNameDefinition : tpDefinitions) { try { ImportPropertyAnagraficaUtil importBean = (ImportPropertyAnagraficaUtil) context .getBean(tpNameDefinition); anagraficaUtils.importProprieta(anagraficaObject, importBean); } catch (Exception ecc) { saveMessage(request, getText("action.file.nosuccess.metadato.upload", new Object[] { ecc.getMessage() }, request.getLocale())); j++; i--; } i++; } //pulisco l'anagrafica anagraficaObject.pulisciAnagrafica(); applicationService.saveOrUpdate(modelClass, anagraficaObject); saveMessage(request, getText("action.file.success.upload", new Object[] { new String("Totale Oggetti Caricati:" + (i + j) + "" + "[" + i + " caricate con successo/" + j + " fallito caricamento]") }, request.getLocale())); return new ModelAndView(getDetailsView()); }
From source file:com.indeed.iupload.web.controller.AppController.java
@RequestMapping(value = "/repository/{repoId}/index/{indexName}/file/", method = RequestMethod.POST) public @ResponseBody BasicResponse executeCreateFile(@PathVariable String repoId, @PathVariable String indexName, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception { if (!checkUserQualification(request, repoId, indexName)) { throw new UnauthorizedOperationException(); }/* w w w .j a va2s .c o m*/ if (file.isEmpty()) { return BasicResponse.error("File is not specified"); } IndexRepository repository = getRepository(repoId); Index index = repository.find(indexName); InputStream is = file.getInputStream(); try { index.createFileToIndex(file.getOriginalFilename(), is); } finally { Closeables2.closeQuietly(is, log); } return BasicResponse.success(null); }
From source file:net.duckling.ddl.web.api.rest.FileEditController.java
@RequestMapping(value = "/files", method = RequestMethod.POST) public void upload(@RequestParam(value = "path", required = false) String path, @RequestParam("file") MultipartFile file, @RequestParam(value = "ifExisted", required = false) String ifExisted, HttpServletRequest request, HttpServletResponse response) throws IOException { String uid = getCurrentUid(request); int tid = getCurrentTid(); path = StringUtils.defaultIfBlank(path, PathName.DELIMITER); Resource parent = folderPathService.getResourceByPath(tid, path); if (parent == null) { writeError(ErrorMsg.NOT_FOUND, response); return;/*from w ww . j a v a 2s. c o m*/ } List<Resource> list = resourceService.getResourceByTitle(tid, parent.getRid(), LynxConstants.TYPE_FILE, file.getOriginalFilename()); if (list.size() > 0 && !IF_EXISTED_UPDATE.equals(ifExisted)) { writeError(ErrorMsg.EXISTED, response); return; } FileVersion fv = null; try { fv = resourceOperateService.upload(uid, super.getCurrentTid(), parent.getRid(), file.getOriginalFilename(), file.getSize(), file.getInputStream()); } catch (NoEnoughSpaceException e) { writeError(ErrorMsg.NO_ENOUGH_SPACE, response); return; } Resource resource = resourceService.getResource(fv.getRid()); resource.setPath(folderPathService.getPathString(resource.getRid())); JsonUtil.write(response, VoUtil.getResourceVo(resource)); }
From source file:com.fengduo.bee.web.controller.upload.FileUploadController.java
@RequestMapping(value = "/Upload", headers = "accept=*/*", produces = "application/json", method = RequestMethod.POST) @ResponseBody// w w w .ja v a 2s.co m public DeferredResult<String> Upload(MultipartFile upload) { DeferredResult<String> deferredResult = new DeferredResult<String>(); long size = upload.getSize(); if (size == 0) { deferredResult.setResult("-1"); return deferredResult; } PicsInfoEnum picInfoEnum = PicsInfoEnum.AVATAR_IMG; if (picInfoEnum == null) { deferredResult.setResult("-1"); return deferredResult; } int maxSize = picInfoEnum.getMaxSize(); if (size > maxSize) { deferredResult.setResult("-1"); return deferredResult; } // ??? String suffix = getSuffix(upload.getOriginalFilename()); boolean isLegal = checkSuffixLegal(picInfoEnum.getSuffixs(), suffix); if (!isLegal) { deferredResult.setResult("-1"); return deferredResult; } long userId = getCurrentUserId(); String relativeUrl = null; relativeUrl = picInfoEnum.getDirPrefix() + "/" + userId + "/"; final String _filePath = relativeUrl; Result result = fileService.createFilePath(upload, new IFileCreate() { public String build(String filePath, String suffix) { return _filePath + filePath + suffix; } }); if (result.isSuccess()) { deferredResult.setResult("http://fengduo.co" + result.getData().toString()); return deferredResult; } else { deferredResult.setResult("IOError"); return deferredResult; } }
From source file:com.iana.dver.controller.DverAdminController.java
@RequestMapping(value = "/admin/bulkChangeOwnerXLS", method = RequestMethod.POST) public @ResponseBody String performBulkChangeOwnerWithXLS(MultipartHttpServletRequest request, HttpServletResponse response) {/*from w w w .jav a 2s. c o m*/ Iterator<String> itr = request.getFileNames(); if (!itr.hasNext()) { return "Please provide XLS file to process."; } MultipartFile bulkFile = request.getFile(itr.next()); logger.info(bulkFile.getOriginalFilename() + " uploaded!"); try { String extension = FilenameUtils.getExtension(bulkFile.getOriginalFilename()); if (extension.equalsIgnoreCase("xls")) { if (bulkFile.getSize() == 0) { return "Uploaded file should not be empty."; } if (bulkFile.getSize() > 2097152) { return "Uploaded file should not exceed 2 MB"; } Map<Integer, String[]> dversToBeProcessed = this.dverDetailsService .findDversForBulkProcessing(bulkFile.getInputStream()); if (dversToBeProcessed.isEmpty()) { return "No DVER's found for 'Change Owner Bulk Processing'."; } else { int successCount = 0; int failCount = 0; StringBuilder failDverDetails = new StringBuilder( "DVER Bulk Change Owner XLS processed successfully. <br/>"); failDverDetails.append( "Following is the list of DVER's which were not processed successfully for Bulk Change Owner: <br/>"); for (Integer dverDetailId : dversToBeProcessed.keySet()) { String[] dots = dversToBeProcessed.get(dverDetailId); RejectedDverVO rejectedDverVO = new RejectedDverVO(); rejectedDverVO.setDverDetailId(dverDetailId); rejectedDverVO.setIepdot(dots[0] != null ? dots[0] : ""); rejectedDverVO.setMcdot(dots[1] != null ? dots[1] : ""); rejectedDverVO.setIepUserId(0); rejectedDverVO.setMcUserId(0); StringBuilder errors = new StringBuilder(); validateDOTFields(rejectedDverVO, errors); if (errors.length() == 0) { this.dverDetailsService.moveRejectedDverToFound(rejectedDverVO, dverDetailId); successCount++; } else { failCount++; failDverDetails.append("(" + failCount + ") "); failDverDetails.append("DverDetailId : " + dverDetailId + " <br/>"); failDverDetails.append("MC DOT: " + rejectedDverVO.getMcdot() + " <br/>"); failDverDetails.append("IEP DOT: " + rejectedDverVO.getMcdot() + " <br/>"); failDverDetails.append("Reason for failure: " + errors.toString() + " <br/>"); } } if (failCount > 0) { logger.info("Fail DVER Notice :" + failDverDetails.toString()); DVERUtil.sendBulkUpdateFailureNotice(failDverDetails.toString()); } return "Change Owner for " + successCount + " DVER's completed successfully. Failed to complete " + failCount + " DVER's due to wrong provided values of IEP/MC DOTs"; } } else { return "The uploaded file type is not allowed."; } } catch (Exception e) { DVERUtil.sendExceptionEmails("upload method of DverAdminController \n " + e); logger.error("Error in submitEditCompanyForAdmin()....." + e); return "The uploaded file could not be processed!!"; } }
From source file:com.mycompany.projetsportmanager.spring.rest.controllers.UserController.java
/** * Affect a image to a specified user//from w w w . j a v a 2s . c o m * * @param userId * the user identifier * @param uploadedInputStream * the image uploaded input stream * @param fileDetail * the image detail format * @return response */ @RequestMapping(method = RequestMethod.POST, value = "/{userId}/picture") @ResponseStatus(HttpStatus.OK) @PreAuthorize(value = "hasRole('AK_ADMIN')") public void pictureUpdate(@PathVariable("userId") Long userId, @RequestParam MultipartFile user_picture) { //Le nom du paramtre correspond au nom du champ de formulaire qu'il faut utiliser !!!! if (user_picture == null || user_picture.isEmpty()) { logger.debug("Incorrect input stream or file name for image of user" + userId); throw new DefaultSportManagerException(new ErrorResource("parameter missing", "Picture should be uploaded as a multipart/form-data file param named user_picture", HttpStatus.BAD_REQUEST)); } if (!(user_picture.getOriginalFilename().endsWith(".jpg") || user_picture.getOriginalFilename().endsWith(".jpeg"))) { logger.debug("File for picture of user" + userId + " must be a JPEG file."); throw new DefaultSportManagerException(new ErrorResource("incorrect file format", "Picture should be a JPG file", HttpStatus.BAD_REQUEST)); } try { userService.addUserPicture(userId, user_picture.getInputStream()); } catch (SportManagerException e) { String msg = "Can't update user picture with id " + userId + " into DB"; logger.error(msg, e); throw new DefaultSportManagerException( new ErrorResource("db error", msg, HttpStatus.INTERNAL_SERVER_ERROR)); } catch (IOException e) { String msg = "Can't update user picture with id " + userId + " because of IO Error"; logger.error(msg, e); throw new DefaultSportManagerException( new ErrorResource("io error", msg, HttpStatus.INTERNAL_SERVER_ERROR)); } }
From source file:com.netflix.genie.web.controllers.JobRestController.java
private ResponseEntity<Void> handleSubmitJob(final JobRequest jobRequest, final MultipartFile[] attachments, final String clientHost, final String userAgent, final HttpServletRequest httpServletRequest) throws GenieException { if (jobRequest == null) { throw new GeniePreconditionException("No job request entered. Unable to submit."); }/*from w w w. j a v a 2 s .c om*/ // get client's host from the context final String localClientHost; if (StringUtils.isNotBlank(clientHost)) { localClientHost = clientHost.split(",")[0]; } else { localClientHost = httpServletRequest.getRemoteAddr(); } final JobRequest jobRequestWithId; // If the job request does not contain an id create one else use the one provided. final String jobId; final Optional<String> jobIdOptional = jobRequest.getId(); if (jobIdOptional.isPresent() && StringUtils.isNotBlank(jobIdOptional.get())) { jobId = jobIdOptional.get(); jobRequestWithId = jobRequest; } else { jobId = UUID.randomUUID().toString(); final JobRequest.Builder builder = new JobRequest.Builder(jobRequest.getName(), jobRequest.getUser(), jobRequest.getVersion(), jobRequest.getCommandArgs(), jobRequest.getClusterCriterias(), jobRequest.getCommandCriteria()).withId(jobId) .withDisableLogArchival(jobRequest.isDisableLogArchival()) .withTags(jobRequest.getTags()).withDependencies(jobRequest.getDependencies()) .withApplications(jobRequest.getApplications()); jobRequest.getCpu().ifPresent(builder::withCpu); jobRequest.getMemory().ifPresent(builder::withMemory); jobRequest.getGroup().ifPresent(builder::withGroup); jobRequest.getSetupFile().ifPresent(builder::withSetupFile); jobRequest.getDescription().ifPresent(builder::withDescription); jobRequest.getEmail().ifPresent(builder::withEmail); jobRequest.getTimeout().ifPresent(builder::withTimeout); jobRequestWithId = builder.build(); } // Download attachments int numAttachments = 0; long totalSizeOfAttachments = 0L; if (attachments != null) { log.info("Saving attachments for job {}", jobId); numAttachments = attachments.length; for (final MultipartFile attachment : attachments) { totalSizeOfAttachments += attachment.getSize(); log.debug("Attachment name: {} Size: {}", attachment.getOriginalFilename(), attachment.getSize()); try { this.attachmentService.save(jobId, attachment.getOriginalFilename(), attachment.getInputStream()); } catch (final IOException ioe) { throw new GenieServerException(ioe); } } } final JobMetadata metadata = new JobMetadata.Builder().withClientHost(localClientHost) .withUserAgent(userAgent).withNumAttachments(numAttachments) .withTotalSizeOfAttachments(totalSizeOfAttachments).build(); this.jobCoordinatorService.coordinateJob(jobRequestWithId, metadata); final HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setLocation( ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(jobId).toUri()); return new ResponseEntity<>(httpHeaders, HttpStatus.ACCEPTED); }
From source file:com.carlos.projects.billing.ExcelToMySQLImporter.java
public Long importData(MultipartFile excelFile) throws ImportException { XSSFWorkbook workbook;/*from w w w . jav a 2s . c o m*/ File componentsFile; try { componentsFile = new File("components-" + new Date().getTime() + ".xlsx"); excelFile.transferTo(componentsFile); workbook = new XSSFWorkbook(componentsFile.getAbsolutePath()); } catch (IOException e) { throw new ImportException(messages.getProperty("import.error"), e); } workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK); Iterator<Row> rowIterator = workbook.getSheetAt(workbook.getActiveSheetIndex()).iterator(); Long numberOfImportedItems = 0L; log.info("Starting reading from file " + excelFile.getOriginalFilename() + " to import components to database"); while (rowIterator.hasNext()) { Row row = rowIterator.next(); String familyCode = row.getCell(FAMILY_CODE).getStringCellValue().trim(); //The first row of the excel file is the one with the titles if (row.getRowNum() != 0 && StringUtils.isNotBlank(familyCode)) { Family family = familyDAO.getById(Family.class, familyCode); boolean saveFamily = false; if (family == null) { family = createFamilyFromRow(row); saveFamily = true; } String componentCode = row.getCell(COMPONENT_CODE).getStringCellValue().trim(); Component component = componentDAO.getById(Component.class, componentCode); boolean addComponent = false; if (component == null) { addComponent = true; component = createComponent(row, family); numberOfImportedItems += 1L; } if (saveFamily) { if (addComponent) { family.addComponent(component); } familyDAO.save(family); log.info("Family " + family + " saved into the database"); } else { componentDAO.save(component); log.info("Component " + component + " saved into the database"); } } } closeAndDeleteTemporaryFiles(componentsFile); log.info("Components import to database finished"); return numberOfImportedItems; }
From source file:com.dlshouwen.jspc.zwpc.controller.SelfEvaluateController.java
private String uploadFile(HttpServletRequest request, String fname) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile(fname); String fileName = multipartFile.getOriginalFilename(); String filePath = ""; if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { filePath = jobj.getString("fpath"); }/*from ww w.ja va 2s . co m*/ } /* if (fileName.trim().length() > 0) { int pos = fileName.lastIndexOf("."); fileName = fileName.substring(pos); String fileDirPath = request.getSession().getServletContext().getRealPath("/"); String path = fileDirPath.substring(0, fileDirPath.lastIndexOf(File.separator)) + CONFIG.UPLOAD_FILE_PATH; Date date = new Date(); fileName = String.valueOf(date.getTime()) + fileName; File file = new File(path); if (!file.exists()) { file.mkdirs(); } file = new File(path + "/" + fileName); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } path = path + "/" + fileName; FileOutputStream fos = null; InputStream s = null; try { fos = new FileOutputStream(file); s = multipartFile.getInputStream(); byte[] buffer = new byte[1024]; int read = 0; while ((read = s.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fos != null) { fos.close(); } if (s != null) { s.close(); } } catch (Exception e) { e.printStackTrace(); } } path = path.replaceAll("\\\\", "/"); filePath = path; } */ return filePath; }