List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:com.qcadoo.mes.basic.controllers.SubassemblyMultiUploadController.java
@ResponseBody @RequestMapping(value = "/multiUploadFilesForSubassembly", method = RequestMethod.POST) public void upload(MultipartHttpServletRequest request, HttpServletResponse response) { Long subassemblyId = Long.parseLong(request.getParameter("techId")); Entity subassembly = dataDefinitionService .get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_SUBASSEMBLY).get(subassemblyId); DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_SUBASSEMBLY_ATTACHMENT); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null; while (itr.hasNext()) { mpf = request.getFile(itr.next()); String path = ""; try {//from w w w.j a v a 2 s . co m path = fileService.upload(mpf); } catch (IOException e) { logger.error("Unable to upload attachment.", e); } if (exts.contains(Files.getFileExtension(path).toUpperCase())) { Entity atchment = attachmentDD.create(); atchment.setField(SubassemblyAttachmentFields.ATTACHMENT, path); atchment.setField(SubassemblyAttachmentFields.NAME, mpf.getOriginalFilename()); atchment.setField(SubassemblyAttachmentFields.SUBASSEMBLY, subassembly); atchment.setField(SubassemblyAttachmentFields.EXT, Files.getFileExtension(path)); BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext()); BigDecimal divider = new BigDecimal(1024, numberService.getMathContext()); BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP); atchment.setField(SubassemblyAttachmentFields.SIZE, size); attachmentDD.save(atchment); } } }
From source file:edu.mayo.qdm.webapp.rest.controller.TranslatorController.java
/** * Creates the exceuction./*from ww w. java 2 s . c o m*/ * * @param request the request * @param startDate the start date * @param endDate the end date * @return the object * @throws Exception the exception */ @SuppressWarnings({ "rawtypes", "unchecked" }) @RequestMapping(value = "/executor/executions", method = RequestMethod.POST) public synchronized Object createExceuction(HttpServletRequest request, final @RequestParam(required = true) String startDate, final @RequestParam(required = true) String endDate, final @RequestParam(required = false) String valueSetDefinitions) throws Exception { //For now, don't validate the date. This requirement may //come back at some point. //this.dateValidator.validateDate(startDate, DateType.START); //this.dateValidator.validateDate(endDate, DateType.END); if (!(request instanceof MultipartHttpServletRequest)) { throw new IllegalStateException("ServletRequest expected to be of type MultipartHttpServletRequest"); } final Map<String, String> valueSetDefinitionsMap = valueSetDefinitions != null ? new ObjectMapper().readValue(valueSetDefinitions, HashMap.class) : Collections.EMPTY_MAP; final MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; final MultipartFile multipartFile = multipartRequest.getFile("file"); final String id = this.idGenerator.getId(); final FileSystemResult result = this.fileSystemResolver.getNewFiles(id); FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), result.getInputQdmXml()); String xmlFileName = multipartFile.getOriginalFilename(); final ExecutionInfo info = new ExecutionInfo(); info.setId(id); info.setStatus(Status.PROCESSING); info.setStart(new Date()); info.setParameters(new Parameters(startDate, endDate, xmlFileName)); this.fileSystemResolver.setExecutionInfo(id, info); this.executorService.submit(new Runnable() { @Override public void run() { ExecutionResult translatorResult = null; try { translatorResult = launcher.launchTranslator(IOUtils.toString(multipartFile.getInputStream()), dateValidator.parse(startDate), dateValidator.parse(endDate), valueSetDefinitionsMap); info.setStatus(Status.COMPLETE); info.setFinish(new Date()); fileSystemResolver.setExecutionInfo(id, info); FileUtils.writeStringToFile(result.getOuptutResultXml(), translatorResult.getXml()); } catch (Exception e) { info.setStatus(Status.FAILED); info.setFinish(new Date()); info.setError(ExceptionUtils.getFullStackTrace(e)); fileSystemResolver.setExecutionInfo(id, info); log.warn(e); throw new RuntimeException(e); } } }); if (this.isHtmlRequest(multipartRequest)) { return new ModelAndView("redirect:/executor/executions"); } else { String locationUrl = "executor/execution/" + id; final HttpHeaders headers = new HttpHeaders(); headers.setLocation(URI.create(locationUrl)); return new ResponseEntity(headers, HttpStatus.CREATED); } }
From source file:org.openmrs.module.visitdocumentsui.ComplexObsSaver.java
public Obs saveImageDocument(Visit visit, Person person, Encounter encounter, String fileCaption, MultipartFile multipartFile, String instructions) throws IOException { conceptComplex = context.getConceptComplex(ContentFamily.IMAGE); prepareComplexObs(visit, person, encounter, fileCaption); Object image = multipartFile.getInputStream(); double compressionRatio = getCompressionRatio(multipartFile.getSize(), 1000000 * context.getMaxStorageFileSize()); if (compressionRatio < 1) { image = Thumbnails.of(ImageIO.read(multipartFile.getInputStream())).scale(compressionRatio) .asBufferedImage();//from w ww.j av a 2s .c o m } obs.setComplexData(complexDataHelper .build(instructions, multipartFile.getOriginalFilename(), image, multipartFile.getContentType()) .asComplexData()); obs = context.getObsService().saveObs(obs, getClass().toString()); return obs; }
From source file:com.hillert.botanic.controller.UploadController.java
/** * Handles image file uplods. Images are persistence to the database using * {@link ImageRepository}.//w w w. j a v a 2s . co m * * @param file Must not be null * @param plantId Must not be null * @return The saved {@link Image} or {@code NULL} in case of a problem. */ @RequestMapping(method = RequestMethod.POST) public Image handleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable("plantId") Long plantId) { if (file.isEmpty()) { return null; } byte[] bytes; try { bytes = file.getBytes(); } catch (IOException e) { throw new IllegalStateException("Error uploading file.", e); } Plant plant = plantRepository.findOne(plantId); if (plant == null) { throw new IllegalStateException(String.format("Plant with id '%s' not found.", plantId)); } Image image = new Image(); image.setImage(bytes); image.setPlant(plant); image.setName(file.getOriginalFilename()); Image savedImage = imageRepository.save(image); Image imageToReturn = new Image(); imageToReturn.setId(savedImage.getId()); imageToReturn.setImage(savedImage.getImage()); imageToReturn.setName(savedImage.getName()); return imageToReturn; }
From source file:com.qcadoo.mes.cmmsMachineParts.controller.PlannedEventMultiUploadController.java
@ResponseBody @RequestMapping(value = "/multiUploadFilesForPlannedEvent", method = RequestMethod.POST) public void upload(MultipartHttpServletRequest request, HttpServletResponse response) { Long eventId = Long.parseLong(request.getParameter("eventId")); Entity event = dataDefinitionService .get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_PLANNED_EVENT) .get(eventId);/* w w w. j a va 2 s . c o m*/ DataDefinition attachmentDD = dataDefinitionService.get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_PLANNED_EVENT_ATTACHMENT); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null; while (itr.hasNext()) { mpf = request.getFile(itr.next()); String path = ""; try { path = fileService.upload(mpf); } catch (IOException e) { logger.error("Unable to upload attachment.", e); } if (exts.contains(Files.getFileExtension(path).toUpperCase())) { Entity atchment = attachmentDD.create(); atchment.setField(PlannedEventAttachmentFields.ATTACHMENT, path); atchment.setField(PlannedEventAttachmentFields.NAME, mpf.getOriginalFilename()); atchment.setField(PlannedEventAttachmentFields.PLANNED_EVENT, event); atchment.setField(PlannedEventAttachmentFields.EXT, Files.getFileExtension(path)); BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext()); BigDecimal divider = new BigDecimal(1024, numberService.getMathContext()); BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP); atchment.setField(PlannedEventAttachmentFields.SIZE, size); atchment = attachmentDD.save(atchment); atchment.isValid(); } } }
From source file:controllers.ProcessController.java
@RequestMapping("management/staffs/add") public ModelAndView staffs(@RequestParam("name") String name, @RequestParam("gender") String genderString, @RequestParam("birthday") String birthdayString, @RequestParam("avatar") MultipartFile avatar, @RequestParam("email") String email, @RequestParam("phone") String phone, @RequestParam("salary") String salaryString, @RequestParam("notes") String notes, @RequestParam("depart") String departId) throws IOException { String avatarFileName = "default-avatar.png"; if (!avatar.isEmpty()) { String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename()); avatar.transferTo(new File(avatarPath)); avatarFileName = new File(avatarPath).getName(); }/*www. j a v a2 s . c om*/ StaffsDAO staffsDAO = new StaffsDAO(); staffsDAO.addStaff(name, genderString, birthdayString, avatarFileName, email, phone, salaryString, notes, departId); return new ModelAndView("redirect:../staffs.htm"); }
From source file:org.ngrinder.script.controller.FileEntryController.java
private void upload(User user, String path, String description, MultipartFile file) throws IOException { FileEntry fileEntry = new FileEntry(); fileEntry.setContentBytes(file.getBytes()); fileEntry.setDescription(description); fileEntry.setPath(FilenameUtils.separatorsToUnix(FilenameUtils.concat(path, file.getOriginalFilename()))); fileEntryService.save(user, fileEntry); }
From source file:de.interactive_instruments.etf.webapp.controller.TestObjectController.java
@RequestMapping(value = "/testobjects/add-file-to", method = RequestMethod.POST) public String addFileTestData(@ModelAttribute("testObject") @Valid TestObjectDto testObject, BindingResult result, MultipartHttpServletRequest request, Model model) throws IOException, URISyntaxException, StoreException, ParseException, NoSuchAlgorithmException { if (SUtils.isNullOrEmpty(testObject.getLabel())) { throw new IllegalArgumentException("Label is empty"); }/*w ww.ja v a 2s . c o m*/ if (result.hasErrors()) { return showCreateDoc(model, testObject); } final GmlAndXmlFilter filter; final String regex = testObject.getProperty("regex"); if (regex != null && !regex.isEmpty()) { filter = new GmlAndXmlFilter(new RegexFileFilter(regex)); } else { filter = new GmlAndXmlFilter(); } // Transfer uploaded data final MultipartFile multipartFile = request.getFile("testObjFile"); if (multipartFile != null && !multipartFile.isEmpty()) { // Transfer file to tmpUploadDir final IFile testObjFile = this.tmpUploadDir .secureExpandPathDown(testObject.getLabel() + "_" + multipartFile.getOriginalFilename()); testObjFile.expectFileIsWritable(); multipartFile.transferTo(testObjFile); final String type; try { type = MimeTypeUtils.detectMimeType(testObjFile); if (!type.equals("application/xml") && !type.equals("application/zip")) { throw new IllegalArgumentException(type + " is not supported"); } } catch (Exception e) { result.reject("l.upload.invalid", new Object[] { e.getMessage() }, "Unable to use file: {0}"); return showCreateDoc(model, testObject); } // Create directory for test data file final IFile testObjectDir = testDataDir .secureExpandPathDown(testObject.getLabel() + ".upl." + getSimpleRandomNumber(4)); testObjectDir.ensureDir(); if (type.equals("application/zip")) { // Unzip files to test directory try { testObjFile.unzipTo(testObjectDir, filter); } catch (IOException e) { try { testObjectDir.delete(); } catch (Exception de) { ExcUtils.supress(de); } result.reject("l.decompress.failed", new Object[] { e.getMessage() }, "Unable to decompress file: {0}"); return showCreateDoc(model, testObject); } finally { // delete zip file testObjFile.delete(); } } else { // Move XML to test directory testObjFile.copyTo(testObjectDir.getPath() + File.separator + multipartFile.getOriginalFilename()); } testObject.addResource("data", testObjectDir.toURI()); testObject.getProperties().setProperty("uploaded", "true"); } else { final URI resURI = testObject.getResourceById("data"); if (resURI == null) { throw new StoreException("Workflow error. Data path resource not set."); } final IFile absoluteTestObjectDir = testDataDir.secureExpandPathDown(resURI.getPath()); testObject.getResources().clear(); testObject.getResources().put(EidFactory.getDefault().createFromStrAsStr("data"), absoluteTestObjectDir.toURI()); // Check if file exists final IFile sourceDir = new IFile(new File(testObject.getResourceById("data"))); try { sourceDir.expectDirIsReadable(); } catch (Exception e) { result.reject("l.testObject.testdir.insufficient.rights", new Object[] { e.getMessage() }, "Insufficient rights to read directory: {0}"); return showCreateDoc(model, testObject); } testObject.getProperties().setProperty("uploaded", "false"); } final FileHashVisitor v = new FileHashVisitor(filter); Files.walkFileTree(new File(testObject.getResourceById("data")).toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), 5, v); if (v.getFileCount() == 0) { if (regex != null && !regex.isEmpty()) { result.reject("l.testObject.regex.null.selection", new Object[] { regex }, "No files were selected with the regular expression \"{0}\"!"); } else { result.reject("l.testObject.testdir.no.xml.gml.found", "No file were found in the directory with a gml or xml file extension"); } return showCreateDoc(model, testObject); } VersionDataDto vd = new VersionDataDto(); vd.setItemHash(v.getHash()); testObject.getProperties().setProperty("files", String.valueOf(v.getFileCount())); testObject.getProperties().setProperty("size", String.valueOf(v.getSize())); testObject.getProperties().setProperty("sizeHR", FileUtils.byteCountToDisplaySize(v.getSize())); testObject.setVersionData(vd); testObject.setId(EidFactory.getDefault().createRandomUuid()); testObjStore.create(testObject); return "redirect:/testobjects"; }
From source file:net.groupbuy.service.impl.ProductImageServiceImpl.java
public void build(ProductImage productImage) { MultipartFile multipartFile = productImage.getFile(); if (multipartFile != null && !multipartFile.isEmpty()) { try {/*w ww . java2 s .com*/ Setting setting = SettingUtils.get(); Map<String, Object> model = new HashMap<String, Object>(); model.put("uuid", UUID.randomUUID().toString()); String uploadPath = FreemarkerUtils.process(setting.getImageUploadPath(), model); String uuid = UUID.randomUUID().toString(); String sourcePath = uploadPath + uuid + "-source." + FilenameUtils.getExtension(multipartFile.getOriginalFilename()); String largePath = uploadPath + uuid + "-large." + DEST_EXTENSION; String mediumPath = uploadPath + uuid + "-medium." + DEST_EXTENSION; String thumbnailPath = uploadPath + uuid + "-thumbnail." + DEST_EXTENSION; Collections.sort(storagePlugins); for (StoragePlugin storagePlugin : storagePlugins) { if (storagePlugin.getIsEnabled()) { File tempFile = new File( System.getProperty("java.io.tmpdir") + "/upload_" + UUID.randomUUID() + ".tmp"); if (!tempFile.getParentFile().exists()) { tempFile.getParentFile().mkdirs(); } multipartFile.transferTo(tempFile); addTask(sourcePath, largePath, mediumPath, thumbnailPath, tempFile, multipartFile.getContentType()); productImage.setSource(storagePlugin.getUrl(sourcePath)); productImage.setLarge(storagePlugin.getUrl(largePath)); productImage.setMedium(storagePlugin.getUrl(mediumPath)); productImage.setThumbnail(storagePlugin.getUrl(thumbnailPath)); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.dlshouwen.wzgl.picture.controller.PictureController.java
/** * //from ww w . j a va 2 s . c om * * @param picture * @param bindingResult ? * @param request * @return ajax? * @throws Exception */ @RequestMapping(value = "/ajaxEdit", method = RequestMethod.POST) @ResponseBody public void ajaxEditPicture(@Valid Picture picture, HttpServletRequest request, BindingResult bindingResult, HttpServletResponse response) throws Exception { // AJAX? AjaxResponse ajaxResponse = new AjaxResponse(); // ?? if (bindingResult.hasErrors()) { ajaxResponse.bindingResultHandler(bindingResult); // ? LogUtils.updateOperationLog(request, OperationType.INSERT, "???" + AjaxResponse.getBindingResultMessage(bindingResult) + ""); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); return; } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("picture"); String fileName = multipartFile.getOriginalFilename(); //? String path = null; if (null != multipartFile && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { JSONObject jobj = FileUploadClient.upFile(request, fileName, multipartFile.getInputStream()); if (jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); } } Picture oldPicture = dao.getPictureById(picture.getPicture_id()); oldPicture.setDescription(picture.getDescription()); oldPicture.setFlag(picture.getFlag()); oldPicture.setOrder(picture.getOrder()); oldPicture.setPicture_name(picture.getPicture_name()); oldPicture.setShow(picture.getShow()); // ?? Date nowDate = new Date(); // picture.setUpdate_time(nowDate); if (null != path) { oldPicture.setPath(path); } try { // dao.updatePicture(picture); // ???? ajaxResponse.setSuccess(true); ajaxResponse.setSuccessMessage("??"); } catch (Exception e) { // ???? ajaxResponse.setError(true); ajaxResponse.setErrorMessage("?"); } //? Map map = new HashMap(); map.put("URL", basePath + "picture"); ajaxResponse.setExtParam(map); // ? LogUtils.updateOperationLog(request, OperationType.INSERT, "?" + picture.getPicture_id()); response.setContentType("text/html;charset=utf-8"); JSONObject obj = JSONObject.fromObject(ajaxResponse); response.getWriter().write(obj.toString()); }