List of usage examples for org.springframework.web.multipart MultipartFile getInputStream
@Override
InputStream getInputStream() throws IOException;
From source file:com.emergya.persistenceGeo.web.RestResourcesController.java
/** * Obtain a resource from a multipart file * /*from ww w . j av a 2 s. c o m*/ * @param file * @param resourceId * * @return resource */ private ResourceDto multipartFileToResource(MultipartFile file, Long resourceId) { // ResourceDto resource = new ResourceDto(); // simple properties resource.setName(file.getOriginalFilename()); resource.setSize(file.getSize()); resource.setType(file.getContentType()); resource.setAccessId(resourceId); // obtain data byte[] data; String extension = "png"; if (resource.getType() != null) { if (resource.getType().split("/").length > 0) { extension = resource.getType().split("/")[resource.getType().split("/").length - 1]; } else { extension = resource.getType(); } } try { data = IOUtils.toByteArray(file.getInputStream()); File temp = com.emergya.persistenceGeo.utils.FileUtils.createFileTemp(resource.getName(), extension); org.apache.commons.io.FileUtils.writeByteArrayToFile(temp, data); resource.setData(temp); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return resource; }
From source file:org.magnum.dataup.VideoSvcUp.java
@RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.POST) public @ResponseBody VideoStatus setVideoData(@PathVariable(VideoSvcApi.ID_PARAMETER) long id, @RequestParam(VideoSvcApi.DATA_PARAMETER) MultipartFile data, HttpServletResponse response) throws IOException { if (!videos.containsKey(id)) { System.out.println("ID Not found"); response.setStatus(HttpStatus.NOT_FOUND.value()); } else {/*ww w. ja v a2 s.co m*/ Video v = videos.get(id); //System.out.println("Vishal's video id: " + v.getId() + " url: " + v.getDataUrl() // + " title:" + v.getTitle() + " Content type:" + v.getContentType() + // " Subject:" + v.getSubject()); videoDataMgr = VideoFileManager.get(); //singleton if (videoDataMgr.hasVideoData(v)) { System.out.println("Notice: Overwriting video at id: " + v.getId()); } videoDataMgr.saveVideoData(v, data.getInputStream()); } return new VideoStatus(VideoState.READY); }
From source file:com.dlshouwen.tdjs.picture.controller.TdjsPictureController.java
/** * /* w ww. j a v a 2s . co m*/ * * @param picture * @param bindingResult ? * @param request * @return ajax? * @throws Exception */ @RequestMapping(value = "/ajaxAdd", method = RequestMethod.POST) @ResponseBody public void ajaxAddPicture(@Valid Picture picture, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws Exception { // AJAX? AjaxResponse ajaxResponse = new AjaxResponse(); // ??zz 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; } String path = ""; MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartFile = multipartRequest.getFile("picture"); if (multipartFile != null && StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { //?? JSONObject jobj = FileUploadClient.upFile(request, multipartFile.getOriginalFilename(), multipartFile.getInputStream()); if (null != jobj && jobj.getString("responseMessage").equals("OK")) { path = jobj.getString("fpath"); } } // ???? SessionUser sessionUser = (SessionUser) request.getSession().getAttribute(CONFIG.SESSION_USER); String userId = sessionUser.getUser_id(); String userName = sessionUser.getUser_name(); Date nowDate = new Date(); // ? picture.setPicture_id(new GUID().toString()); picture.setCreate_time(nowDate); picture.setUser_id(userId); picture.setUser_name(userName); path = path.replaceAll("\\\\", "/"); picture.setPath(path); // dao.insertPicture(picture); // ???? ajaxResponse.setSuccess(true); ajaxResponse.setSuccessMessage("??"); //? Map map = new HashMap(); map.put("URL", "tdjs/tdjsPicture/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()); }
From source file:edu.wisc.doit.tcrypt.controller.EncryptController.java
@RequestMapping(value = "/encryptFile", method = RequestMethod.POST) public ModelAndView encryptFile(@RequestParam("fileToEncrypt") MultipartFile file, @RequestParam("selectedServiceName") String serviceName, HttpServletResponse response) throws Exception { if (file.isEmpty()) { ModelAndView modelAndView = encryptTextInit(); modelAndView.addObject("selectedServiceName", serviceName); return modelAndView; }// w w w .j a va 2 s.c om final FileEncrypter fileEncrypter = this.getFileEncrypter(serviceName); final String filename = FilenameUtils.getName(file.getOriginalFilename()); response.setHeader("Content-Type", "application/x-tar"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".tar" + "\""); final long size = file.getSize(); try (final InputStream inputStream = file.getInputStream(); final ServletOutputStream outputStream = response.getOutputStream()) { fileEncrypter.encrypt(filename, (int) size, inputStream, outputStream); } return null; }
From source file:org.openmrs.module.sync.web.controller.StatusListController.java
/** * The onSubmit function receives the form/command object that was modified by the input form * and saves it to the db/*from w w w .j a v a2 s .c o m*/ * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) */ protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { ModelAndView result = new ModelAndView(new RedirectView(getSuccessView())); // TODO - replace with privilege check if (!Context.isAuthenticated()) throw new APIAuthenticationException("Not authenticated!"); RemoteServer parent = null; HttpSession httpSession = request.getSession(); String success = ""; String error = ""; MessageSourceAccessor msa = getMessageSourceAccessor(); String action = ServletRequestUtils.getStringParameter(request, "action", ""); SyncService syncService = Context.getService(SyncService.class); if ("resetAttempts".equals(action)) { List<SyncRecord> syncRecords = syncService.getSyncRecords(SyncRecordState.FAILED_AND_STOPPED); for (SyncRecord syncRecord : syncRecords) { syncRecord.setState(SyncRecordState.FAILED); syncRecord.setRetryCount(0); syncService.updateSyncRecord(syncRecord); } success = msa.getMessage("sync.status.transmission.reset.attempts.success", new Object[] { syncRecords.size() }); result.addObject("mode", request.getParameter("mode")); } else if ("createTx".equals(action)) { // handle transmission generation try { parent = syncService.getParentServer(); if (parent == null) { throw new SyncException( "Could not retrieve information about the parent server; null returned."); } // we are creating a sync-transmission, so start by generating a SyncTransmission object // and this is a sychronization via file due the value of action being createTx SyncTransmission tx = SyncUtilTransmission.createSyncTransmission(parent, true, SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_FILE)); String toTransmit = null; // the actual text that will be sent (either an ST or an STR) // Pull out the committed records from parent that haven't been sent back for confirmation // these are all the records we've received and are not sending a confirmation of receipt List<SyncImportRecord> syncImportRecords = syncService .getSyncImportRecords(SyncRecordState.COMMITTED, SyncRecordState.ALREADY_COMMITTED); SyncTransmissionResponse str = new SyncTransmissionResponse(); str.setState(SyncTransmissionState.OK); str.setSyncImportRecords(syncImportRecords); //note: this is transmission *response* object: as in child's response to parent //so the target/source is viewed from 'parent' perspective, //hence for responses the target ID contains the server that generated the response //in this case that means: the target uuid is current server (child) uuid and source uuid is the parent str.setSyncSourceUuid(tx.getSyncTargetUuid()); str.setSyncTargetUuid(tx.getSyncSourceUuid()); str.setSyncTransmission(tx); str.setTimestamp(tx.getTimestamp()); str.setUuid(tx.getUuid()); str.setFileName(""); //of no relevance; we're not saving to file system str.createFile(false); toTransmit = str.getFileOutput(); // Record last attempt parent.setLastSync(new Date()); syncService.saveRemoteServer(parent); // Write text to response InputStream in = new ByteArrayInputStream(toTransmit.getBytes()); response.setContentType("text/xml; charset=utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + tx.getFileName() + ".xml"); OutputStream out = response.getOutputStream(); IOUtils.copy(in, out); out.flush(); out.close(); for (SyncImportRecord record : syncImportRecords) { record.setState(SyncRecordState.COMMITTED_AND_CONFIRMATION_SENT); syncService.updateSyncImportRecord(record); } // don't return a model/view - we'll need to return a file instead. result = null; } catch (Exception e) { e.printStackTrace(); error = msa.getMessage("sync.status.createTx.error"); } } else if ("uploadResponse".equals(action) && request instanceof MultipartHttpServletRequest) { try { String contents = ""; parent = syncService.getParentServer(); // first, get contents of file that is being uploaded. it is clear we are uploading a response from parent at this point MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartSyncFile = multipartRequest.getFile("syncResponseFile"); if (multipartSyncFile != null && !multipartSyncFile.isEmpty()) { InputStream inputStream = null; StringBuilder sb = new StringBuilder(); try { inputStream = multipartSyncFile.getInputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(inputStream, SyncConstants.UTF8)); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); } contents = sb.toString(); } catch (Exception e) { log.error("Unable to read in sync data file", e); error = e.getMessage(); } finally { try { if (inputStream != null) inputStream.close(); } catch (IOException io) { log.error("Unable to close temporary input stream", io); } } } if (contents.length() > 0) { SyncTransmissionResponse str = SyncDeserializer.xmlToSyncTransmissionResponse(contents); int numCommitted = 0; int numAlreadyCommitted = 0; int numFailed = 0; int numOther = 0; if (str.getSyncImportRecords() == null) log.debug("No records to process in response"); else { // process each incoming syncImportRecord, this is just status update for (SyncImportRecord importRecord : str.getSyncImportRecords()) { Context.getService(SyncIngestService.class).processSyncImportRecord(importRecord, parent); } } try { // store this file on filesystem too str.createFile(false, SyncConstants.DIR_JOURNAL); } catch (Exception e) { log.error("Unable to create file to store SyncTransmissionResponse: " + str.getFileName()); e.printStackTrace(); } // now pull out the data that originated on the 'source' server and try to process it SyncTransmission st = str.getSyncTransmission(); // now process the syncTransmission if one was received if (st != null) { str = SyncUtilTransmission.processSyncTransmission(st, SyncUtil .getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_FILE)); // get some numbers about what was just processed to show user the results if (str.getSyncImportRecords() != null) { for (SyncImportRecord importRecord : str.getSyncImportRecords()) { if (importRecord.getState().equals(SyncRecordState.COMMITTED)) numCommitted++; else if (importRecord.getState().equals(SyncRecordState.ALREADY_COMMITTED)) numAlreadyCommitted++; else if (importRecord.getState().equals(SyncRecordState.FAILED)) numFailed++; else numOther++; } } } Object[] args = { numCommitted, numFailed, numAlreadyCommitted, numOther }; success = msa.getMessage("sync.status.uploadResponse.success", args); } else { error = msa.getMessage("sync.status.uploadResponse.fileEmpty"); } } catch (Exception e) { e.printStackTrace(); error = msa.getMessage("sync.status.uploadResponse.error"); } } if (!success.equals("")) httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success); if (!error.equals("")) httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error); return result; }
From source file:miage.ecom.web.admin.controller.ProductImage.java
@RequestMapping(value = "/product/{id}/image", method = RequestMethod.POST) public ResponseEntity<String> create(@PathVariable("id") int productId, @RequestParam("image") MultipartFile image) { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Content-type", "text/html"); String success = null;//from www . ja v a2s.co m String msg = null; String imageUrl = ""; Product product = productFacade.find(productId); if (product == null) { success = "false"; msg = "Ce produit n'existe pas / plus"; } if (image.isEmpty()) { success = "false"; msg = "Impossible de sauvegarder l'image"; } if (!image.getContentType().contains("image")) { success = "false"; msg = "Format de fichier non valide"; } if (success == null) { try { URL thumbUrl = imageManager.uploadThumb(image.getInputStream(), 200); if (thumbUrl != null) { imageUrl = thumbUrl.toString(); product.setImage(imageUrl); productFacade.edit(product); success = "true"; } else { success = "false"; msg = "Impossible de gnrer l'image"; } } catch (Exception ex) { success = "false"; msg = "Impossible de gnrer l'image : " + ex.getMessage(); } } return new ResponseEntity<String>( "{success:" + success + ",msg:\"" + msg + "\",image:\"" + imageUrl + "\"}", responseHeaders, HttpStatus.OK); }
From source file:com.devnexus.ting.web.controller.admin.SponsorController.java
@RequestMapping(value = "/s/admin/{eventKey}/sponsor", method = RequestMethod.POST) public String addSponsor(@RequestParam MultipartFile pictureFile, @Valid Sponsor sponsorForm, BindingResult result, HttpServletRequest request, RedirectAttributes redirectAttributes, @PathVariable("eventKey") String eventKey) { if (request.getParameter("cancel") != null) { return "redirect:/s/admin/{eventKey}/sponsors"; }// w w w . ja v a 2s. c om if (result.hasErrors()) { return "/admin/add-sponsor"; } final Event currentEvent = businessService.getEventByEventKey(eventKey); sponsorForm.setEvent(currentEvent); if (pictureFile != null && pictureFile.getSize() > 0) { final FileData pictureData = new FileData(); try { pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream())); pictureData.setFileSize(pictureFile.getSize()); pictureData.setFileModified(new Date()); pictureData.setName(pictureFile.getOriginalFilename()); pictureData.setType(pictureFile.getContentType()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } sponsorForm.setLogo(pictureData); } final Sponsor savedSponsor = businessService.saveSponsor(sponsorForm); redirectAttributes.addFlashAttribute("successMessage", String.format("The sponsor '%s' was added successfully.", savedSponsor.getName())); return "redirect:/s/admin/{eventKey}/sponsors"; }
From source file:com.devnexus.ting.web.controller.admin.SpeakerController.java
@RequestMapping(value = "/s/admin/speaker", method = RequestMethod.POST) public String addSpeaker(@RequestParam MultipartFile pictureFile, @Valid Speaker speakerForm, BindingResult result, HttpServletRequest request, RedirectAttributes redirectAttributes) { Event currentEvent = this.businessService.getCurrentEvent(); redirectAttributes.addAttribute("eventKey", currentEvent.getEventKey()); if (request.getParameter("cancel") != null) { return "redirect:/s/admin/{eventKey}/speakers"; }/*from w w w .j av a2 s. c om*/ if (result.hasErrors()) { return "/admin/add-speaker"; } if (pictureFile != null && pictureFile.getSize() > 0) { final FileData pictureData = new FileData(); try { pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream())); pictureData.setFileSize(pictureFile.getSize()); pictureData.setFileModified(new Date()); pictureData.setName(pictureFile.getOriginalFilename()); pictureData.setType(pictureFile.getContentType()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } speakerForm.setPicture(pictureData); } final Speaker savedSpeaker = businessService.saveSpeaker(speakerForm); redirectAttributes.addFlashAttribute("successMessage", String.format("The speaker '%s' was added successfully.", savedSpeaker.getFirstLastName())); return "redirect:/s/admin/{eventKey}/speakers"; }
From source file:cn.lhfei.fu.service.impl.ThesisBaseServiceImpl.java
@Override public boolean update(ThesisBaseModel model, String userType) throws Exception { OutputStream out = null;//from w w w . java 2 s . c o m BufferedOutputStream bf = null; Date currentTime = new Date(); boolean result = false; List<MultipartFile> files = model.getFiles(); try { boolean modelIsValid = this.updateThesis(model); if (!modelIsValid) { return result; } int num = 1; for (MultipartFile file : files) {// save archive file if (file.getSize() > 0) { String filePath = filePathBuilder.buildThesisFullPath(model, model.getStudentName()); String fileName = filePathBuilder.buildThesisFileName(model, model.getStudentName(), num); String[] names = file.getOriginalFilename().split("[.]"); String fileType = names[names.length - 1]; String fullPath = filePath + File.separator + fileName + "." + fileType; out = new FileOutputStream(new File(fullPath)); bf = new BufferedOutputStream(out); IOUtils.copyLarge(file.getInputStream(), bf); ThesisArchive archive = new ThesisArchive(); archive.setThesisBaseId(model.getBaseId()); archive.setStudentId(model.getStudentId()); archive.setArchiveName(fileName); archive.setArchivePath(fullPath); archive.setCreateTime(currentTime); archive.setModifyTime(currentTime); archive.setStudentBaseId(model.getStudentBaseId()); archive.setThesisTitle(model.getThesisTitle()); archive.setExtend(model.getThesisEnTitle()); // archive.setExtend1(model.getThesisType()); // // ? if (userType != null && userType.equals(UserTypeEnum.STUDENT.getCode())) { archive.setStatus("" + ApproveStatusEnum.DSH.getCode()); } else if (userType != null && userType.equals(UserTypeEnum.TEACHER.getCode())) { archive.setStatus("" + ApproveStatusEnum.DSH.getCode()); } else if (userType != null && userType.equals(UserTypeEnum.ADMIN.getCode())) { archive.setStatus("" + ApproveStatusEnum.YSH.getCode()); } thesisArchiveDAO.save(archive); // auto increment archives number. num++; } } result = true; } catch (IOException e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage(), e); } catch (NullPointerException e) { log.error("File name arguments missed.", e); throw new NullPointerException(e.getMessage()); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } if (bf != null) { try { bf.flush(); bf.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } return result; }
From source file:org.jodconverter.sample.springboot.ConverterController.java
@PostMapping("/converter") public Object convert(@RequestParam("inputFile") final MultipartFile inputFile, @RequestParam(name = "outputFormat", required = false) final String outputFormat, final RedirectAttributes redirectAttributes) { if (inputFile.isEmpty()) { redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select a file to upload."); return ON_ERROR_REDIRECT; }/*from w w w . j a va2 s. c o m*/ if (StringUtils.isBlank(outputFormat)) { redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Please select an output format."); return ON_ERROR_REDIRECT; } // Here, we could have a dedicated service that would convert document try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { final DocumentFormat targetFormat = DefaultDocumentFormatRegistry.getFormatByExtension(outputFormat); converter.convert(inputFile.getInputStream()) .as(DefaultDocumentFormatRegistry .getFormatByExtension(FilenameUtils.getExtension(inputFile.getOriginalFilename()))) .to(baos).as(targetFormat).execute(); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType(targetFormat.getMediaType())); headers.add("Content-Disposition", "attachment; filename=" + FilenameUtils.getBaseName(inputFile.getOriginalFilename()) + "." + targetFormat.getExtension()); return new ResponseEntity<>(baos.toByteArray(), headers, HttpStatus.OK); } catch (OfficeException | IOException e) { redirectAttributes.addFlashAttribute(ATTRNAME_ERROR_MESSAGE, "Unable to convert the file " + inputFile.getOriginalFilename() + ". Cause: " + e.getMessage()); } return ON_ERROR_REDIRECT; }