List of usage examples for org.springframework.web.multipart MultipartFile getInputStream
@Override
InputStream getInputStream() throws IOException;
From source file:fr.univrouen.poste.web.membre.PosteAPourvoirController.java
@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html") @PreAuthorize("hasPermission(#id, 'manageposte')") public String addFile(@PathVariable("id") Long id, @Valid PosteAPourvoirFile posteFile, BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException { if (bindingResult.hasErrors()) { logger.warn(bindingResult.getAllErrors()); return "redirect:/posteapourvoirs/" + id.toString(); }/*from w w w .ja v a 2 s .co m*/ uiModel.asMap().clear(); PosteAPourvoir poste = PosteAPourvoir.findPosteAPourvoir(id); // upload file MultipartFile file = posteFile.getFile(); // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ? if (file != null) { String filename = file.getOriginalFilename(); boolean filenameAlreadyUsed = false; for (PosteAPourvoirFile pcFile : poste.getPosteFiles()) { if (pcFile.getFilename().equals(filename)) { filenameAlreadyUsed = true; break; } } if (filenameAlreadyUsed) { uiModel.addAttribute("filename_already_used", filename); logger.warn("Upload Restriction sur '" + filename + "' un fichier de mme nom existe dj pour le poste " + poste.getNumEmploi()); } else { Long fileSize = file.getSize(); if (fileSize != 0) { String contentType = file.getContentType(); // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted contentType = contentType.replaceAll(":.*", ""); logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType=" + contentType); InputStream inputStream = file.getInputStream(); //byte[] bytes = IOUtils.toByteArray(inputStream); posteFile.setFilename(filename); posteFile.setFileSize(fileSize); posteFile.setContentType(contentType); logger.info("Upload and set file in DB with filesize = " + fileSize); posteFile.getBigFile().setBinaryFileStream(inputStream, fileSize); posteFile.getBigFile().persist(); Calendar cal = Calendar.getInstance(); Date currentTime = cal.getTime(); posteFile.setSendTime(currentTime); poste.getPosteFiles().add(posteFile); poste.persist(); logService.logActionPosteFile(LogService.UPLOAD_ACTION, poste, posteFile, request, currentTime); } } } else { String userId = SecurityContextHolder.getContext().getAuthentication().getName(); String ip = request.getRemoteAddr(); String userAgent = request.getHeader("User-Agent"); logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent); } return "redirect:/posteapourvoirs/" + id.toString(); }
From source file:fr.hoteia.qalingo.web.mvc.controller.catalog.AssetController.java
@RequestMapping(value = "/asset-form.html*", method = RequestMethod.POST) public ModelAndView assetEdit(final HttpServletRequest request, final HttpServletResponse response, @Valid AssetForm assetForm, BindingResult result, ModelMap modelMap) throws Exception { if (result.hasErrors()) { return display(request, response, modelMap); }/*w ww .j a v a 2 s .c o m*/ final String currentAssetId = assetForm.getId(); final Asset asset = productMarketingService.getProductMarketingAssetById(currentAssetId); final String currentAssetCode = asset.getCode(); MultipartFile multipartFile = assetForm.getFile(); if (multipartFile != null) { long size = multipartFile.getSize(); asset.setFileSize(size); } try { if (multipartFile.getSize() > 0) { String pathProductMarketingImage = multipartFile.getOriginalFilename(); String assetFileRootPath = engineSettingService.getAssetFileRootPath().getDefaultValue(); assetFileRootPath.replaceAll("\\\\", "/"); if (assetFileRootPath.endsWith("/")) { assetFileRootPath = assetFileRootPath.substring(0, assetFileRootPath.length() - 1); } String assetProductMarketingFilePath = engineSettingService.getAssetProductMarketingFilePath() .getDefaultValue(); assetProductMarketingFilePath.replaceAll("\\\\", "/"); if (assetProductMarketingFilePath.endsWith("/")) { assetProductMarketingFilePath = assetProductMarketingFilePath.substring(0, assetProductMarketingFilePath.length() - 1); } if (!assetProductMarketingFilePath.startsWith("/")) { assetProductMarketingFilePath = "/" + assetProductMarketingFilePath; } String absoluteFilePath = assetFileRootPath + assetProductMarketingFilePath + "/" + asset.getType().getPropertyKey().toLowerCase() + "/" + pathProductMarketingImage; InputStream inputStream = multipartFile.getInputStream(); URI url = new URI(absoluteFilePath); File fileAsset; try { fileAsset = new File(url); } catch (IllegalArgumentException e) { fileAsset = new File(url.getPath()); } OutputStream outputStream = new FileOutputStream(fileAsset); int readBytes = 0; byte[] buffer = new byte[8192]; while ((readBytes = inputStream.read(buffer, 0, 8192)) != -1) { outputStream.write(buffer, 0, readBytes); } outputStream.close(); inputStream.close(); asset.setPath(pathProductMarketingImage); } // UPDATE ASSET webBackofficeService.updateProductMarketingAsset(asset, assetForm); } catch (Exception e) { LOG.error("Can't save/update asset file!", e); } final String urlRedirect = backofficeUrlService.buildAssetDetailsUrl(currentAssetCode); return new ModelAndView(new RedirectView(urlRedirect)); }
From source file:org.kew.rmf.reconciliation.ws.MatchController.java
/** * Matches the records in the uploaded file. * * Results are put into a temporary file (available for download) and also shown in the web page. *///from w ww . j a va 2 s .c o m @RequestMapping(value = "/filematch/{configName}", method = RequestMethod.POST) public String doFileMatch(@PathVariable String configName, @RequestParam("file") MultipartFile file, HttpServletResponse response, Model model) { logger.info("{}: File match query {}", configName, file); // Map of matches // Key is the ID of supplied records // Entries are a List of Map<String,String> Map<String, List<Map<String, String>>> matches = new HashMap<String, List<Map<String, String>>>(); // Map of supplied data (useful for display) List<Map<String, String>> suppliedData = new ArrayList<Map<String, String>>(); // Temporary file for results File resultsFile; List<String> properties = new ArrayList<String>(); if (!file.isEmpty()) { try { logger.debug("Looking for : " + configName); LuceneMatcher matcher = reconciliationService.getMatcher(configName); if (matcher != null) { resultsFile = File.createTempFile("match-results-", ".csv"); OutputStreamWriter resultsFileWriter = new OutputStreamWriter(new FileOutputStream(resultsFile), "UTF-8"); resultsFileWriter.write("queryId,matchId\n"); // TODO: attempt to use same line ending as input file // Save the property names: for (Property p : matcher.getConfig().getProperties()) { properties.add(p.getQueryColumnName()); } CsvPreference customCsvPref = new CsvPreference.Builder('"', ',', "\n").build(); CsvMapReader mr = new CsvMapReader(new InputStreamReader(file.getInputStream(), "UTF-8"), customCsvPref); final String[] header = mr.getHeader(true); Map<String, String> record = null; while ((record = mr.read(header)) != null) { logger.debug("Next record is {}", record); suppliedData.add(record); try { List<Map<String, String>> theseMatches = matcher.getMatches(record); // Just write out some matches to std out: if (theseMatches != null) { logger.debug("Record ID {}, matched: {}", record.get("id"), theseMatches.size()); } else { logger.debug("Record ID {}, matched: null", record.get("id")); } matches.put(record.get("id"), theseMatches); // Append matche results to file StringBuilder sb = new StringBuilder(); for (Map<String, String> result : theseMatches) { if (sb.length() > 0) sb.append('|'); sb.append(result.get("id")); } sb.insert(0, ',').insert(0, record.get("id")).append("\n"); resultsFileWriter.write(sb.toString()); } catch (TooManyMatchesException | MatchExecutionException e) { logger.error("Problem handling match", e); } } mr.close(); resultsFileWriter.close(); logger.debug("got file's bytes"); model.addAttribute("resultsFile", resultsFile.getName()); response.setHeader("X-File-Download", resultsFile.getName()); // Putting this in a header saves the unit tests from needing to parse the HTML. } model.addAttribute("suppliedData", suppliedData); model.addAttribute("matches", matches); model.addAttribute("properties", properties); } catch (Exception e) { logger.error("Problem reading file", e); } } return "file-matcher-results"; }
From source file:org.dspace.app.webui.cris.controller.NewImportFormController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { Context dspaceContext = UIUtil.obtainContext(request); ImportDTO object = (ImportDTO) command; MultipartFile fileDTO = object.getFile(); // read folder from configuration and make dir String path = ConfigurationManager.getProperty(CrisConstants.CFG_MODULE, "researcherpage.file.import.path"); File dir = new File(path); dir.mkdir();//from www. ja va2 s . c om try { if (object.getModeXSD() != null) { response.setContentType("application/xml;charset=UTF-8"); response.addHeader("Content-Disposition", "attachment; filename=rp.xsd"); String nameXSD = "xsd-download-webuirequest.xsd"; File filexsd = new File(dir, nameXSD); filexsd.createNewFile(); ImportExportUtils.newGenerateXSD(response.getWriter(), dir, applicationService.findAllContainables(RPPropertiesDefinition.class), filexsd, new String[] { "crisobjects", "crisobject" }, "rp:", "http://www.cilea.it/researcherpage/schemas", "http://www.cilea.it/researcherpage/schemas", new String[] { "publicID", "uuid", "businessID", "type" }, new boolean[] { false, false, true, true }); response.getWriter().flush(); response.getWriter().close(); return null; } else { if (fileDTO != null && !fileDTO.getOriginalFilename().isEmpty()) { Boolean defaultStatus = ConfigurationManager.getBooleanProperty(CrisConstants.CFG_MODULE, "researcherpage.file.import.rpdefaultstatus"); if (AuthorizeManager.isAdmin(dspaceContext)) { dspaceContext.turnOffAuthorisationSystem(); } ImportExportUtils.importResearchersXML(fileDTO.getInputStream(), dir, applicationService, dspaceContext, defaultStatus); saveMessage(request, getText("action.import.with.success", request.getLocale())); } } } catch (Exception e) { log.error(e.getMessage(), e); saveMessage(request, getText("action.import.with.noSuccess", e.getMessage(), request.getLocale())); } return new ModelAndView(getSuccessView()); }
From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java
@RequestMapping(value = "/action/database/{databaseName}/uploadLightside", headers = "content-type=multipart/*", method = RequestMethod.POST) @ResponseBody//www . j a v a2 s . c om PagedResources<Resource<BrowsingLightsideStubsResource>> uploadLightside( @RequestParam("file_annotatedFileForUpload") MultipartFile file_annotatedFileForUpload, @PathVariable("databaseName") String databaseName, HttpServletRequest hsr, HttpSession session) throws IOException { registerDb(hsr, session, databaseName); String lsDataDirectory = lsDataDirectory(); logger.info("Someone uploaded something!"); if (!file_annotatedFileForUpload.isEmpty()) { try { logger.info("Not even empty!"); File tempUpload = File.createTempFile("temp-file-name", ".csv"); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(tempUpload)); FileCopyUtils.copy(file_annotatedFileForUpload.getInputStream(), stream); stream.close(); lightsideService.importAnnotatedData(tempUpload.toString()); } catch (Exception e) { logger.error("Error importing to lightside: " + e); } } return lightsideExports(databaseName, hsr, session); }
From source file:com.wonders.bud.freshmommy.web.content.controller.ChannelController.java
/** * <p>//from w w w. ja va 2 s. c o m * Description:[?] * </p> * * Created by [Dy] [20141124] * Midified by [] [] * @param request * @param response * @param session * @return * @throws Exception * @throws IOException */ @RequestMapping(value = "/addImg", method = RequestMethod.POST) @ResponseBody public RestMsg<Map<String, String>> addImg(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception, IOException { RestMsg<Map<String, String>> rm = new RestMsg<Map<String, String>>(); try { // MultipartHttpRequest MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // MultipartFile file = multipartRequest.getFile("imgfile"); if (file.getContentType().toLowerCase().indexOf("image") < 0) { rm = rm.errorMsg("??"); } else { // ?? String actionPath = request.getSession().getServletContext().getRealPath(""); String uuid = UUID.randomUUID().toString(); // StringBuffer fileName = new StringBuffer(); fileName.append(actionPath).append(File.separator).append(CHANNAL_FILE).append(uuid).append(".png"); // StringBuffer minFileName = new StringBuffer(); minFileName.append(actionPath).append(File.separator).append(CHANNAL_MIN_FILE).append(uuid) .append(".png"); File imgFolder = new File(fileName.toString()); if (!imgFolder.getParentFile().exists()) { // imgFolder.getParentFile().mkdirs(); } File minImgFolder = new File(minFileName.toString()); if (!minImgFolder.getParentFile().exists()) { // minImgFolder.getParentFile().mkdirs(); } // BufferedImage sourceImg = ImageIO.read(file.getInputStream()); float heigth = sourceImg.getHeight(); float width = sourceImg.getWidth(); double scale = 1; double sH = heigth / 200; double sW = width / 200; scale = sH < sW ? sH : sW; int rheigth = new Double(scale * 200).intValue(); int rwidth = new Double(scale * 200).intValue(); //? Thumbnails.of(file.getInputStream()).scale(1).toFile(fileName.toString()); Thumbnails.of(file.getInputStream()).sourceRegion(Positions.CENTER, rwidth, rheigth).size(200, 200) .keepAspectRatio(false).toFile(minFileName.toString()); Map<String, String> map = new HashMap<String, String>(); map.put("minImg", CHANNAL_MIN_FILE + uuid + ".png"); map.put("img", CHANNAL_FILE + uuid + ".png"); rm = rm.successMsg(); rm.setResult(map); } } catch (Exception e) { log.error(e.getLocalizedMessage()); rm.errorMsg("?"); } return rm; }
From source file:com.sccl.attech.modules.sys.web.LoginController.java
@RequestMapping("upload.htm/{referenceId}/{tableName}/{businessType}/{pathName}/{num}") @ResponseBody/* w ww. j a va2 s. c om*/ public String upload(MultipartFile file, @RequestParam(defaultValue = "other", required = false) String group, @PathVariable("referenceId") String referenceId, @PathVariable("tableName") String tableName, @PathVariable("businessType") String businessType, @PathVariable("pathName") String pathName, @PathVariable("num") String num) { String fileName = ""; if (null == file || file.isEmpty()) { System.out.println(""); } else { /*System.out.println(referenceId); System.out.println(tableName); System.out.println(EncodedUtil.encodeValue(businessType)); System.out.println(EncodedUtil.encodeValue(pathName));*/ //String realPath = SpringContextHolder.getRootRealPath() + Global.getCkBaseDir(); String realPath = Global.getCkBaseDir(); if ("".equals(pathName) || pathName == null) { fileName = group + File.separator + DateUtils.getDate("yyyyMM") + File.separator + DateUtils.getDay() + File.separator + RandomUtils.nextLong() + "." + FilenameUtils.getExtension(file.getOriginalFilename()); } else { fileName = EncodedUtil.encodeValue(pathName) + File.separator + DateUtils.getDate("yyyyMM") + File.separator + DateUtils.getDay() + File.separator + RandomUtils.nextLong() + "." + FilenameUtils.getExtension(file.getOriginalFilename()); } // ??IO?FileUtils.copyInputStreamToFile()IO????? try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, fileName)); fileName = Global.getCkBaseDir() + fileName.replace("\\", "/"); } catch (IOException e) { e.printStackTrace(); } return fileName; } return fileName; }
From source file:com.devnexus.ting.web.controller.admin.OrganizerController.java
@RequestMapping(value = "/s/admin/organizer/{organizerId}", method = RequestMethod.POST) public String editOrganizer(@PathVariable("organizerId") Long organizerId, @RequestParam MultipartFile pictureFile, @Valid Organizer organizerForm, BindingResult result, RedirectAttributes redirectAttributes, HttpServletRequest request) { if (request.getParameter("cancel") != null) { return "redirect:/s/admin/index"; }/*from www . j a va2s . com*/ if (result.hasErrors()) { return "/admin/add-organizer"; } final Organizer organizerFromDb = businessService.getOrganizerWithPicture(organizerId); if (request.getParameter("delete") != null) { businessService.deleteOrganizer(organizerFromDb); //FlashMap.setSuccessMessage("The organizer was deleted successfully."); return "redirect:/s/admin/organizers"; } organizerFromDb.setBio(organizerForm.getBio()); organizerFromDb.setFirstName(organizerForm.getFirstName()); organizerFromDb.setLastName(organizerForm.getLastName()); organizerFromDb.setCompany(organizerForm.getCompany()); organizerFromDb.setGooglePlusId(organizerForm.getGooglePlusId()); organizerFromDb.setLinkedInId(organizerForm.getLinkedInId()); organizerFromDb.setTwitterId(organizerForm.getTwitterId()); organizerFromDb.setLanyrdId(organizerForm.getLanyrdId()); organizerFromDb.setGithubId(organizerForm.getGithubId()); organizerFromDb.setSortOrder(organizerForm.getSortOrder()); if (pictureFile != null && pictureFile.getSize() > 0) { final FileData pictureData; if (organizerFromDb.getPicture() == null) { pictureData = new FileData(); } else { pictureData = organizerFromDb.getPicture(); } try { pictureData.getId(); pictureData.setFileData(IOUtils.toByteArray(pictureFile.getInputStream())); pictureData.setFileSize(pictureFile.getSize()); pictureData.setFileModified(new Date()); pictureData.setName(pictureFile.getOriginalFilename()); } catch (IOException e) { throw new IllegalStateException( "Error while processing image for speaker " + organizerForm.getFirstLastName(), e); } organizerForm.setPicture(pictureData); String message = "File '" + organizerForm.getPicture().getName() + "' uploaded successfully"; redirectAttributes.addFlashAttribute("successMessage", message); } businessService.saveOrganizer(organizerFromDb); redirectAttributes.addFlashAttribute("successMessage", "The organizer was edited successfully."); return "redirect:/s/admin/organizers"; }
From source file:com.jd.survey.web.settings.DataSetController.java
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html") public String importDatasetItems(@RequestParam("file") MultipartFile file, @RequestParam("id") Long dataSetId, @RequestParam("ignoreFirstRow") Boolean ignoreFirstRow, @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { try {//from w w w. ja va 2 s.com String login = principal.getName(); User user = userService.user_findByLogin(login); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { log.info(file.getContentType()); //if file is empty OR the file type is incorrect the upload page is returned with an error message. if (file.isEmpty() || !((file.getContentType().equalsIgnoreCase("text/csv")) || (file.getContentType().equals("application/vnd.ms-excel")) || (file.getContentType().equals("text/plain")))) { uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId)); uiModel.addAttribute("emptyFileError", true); return "settings/datasets/upload"; } try { CSVReader csvReader; csvReader = new CSVReader(new InputStreamReader(file.getInputStream())); surveySettingsService.importDatasetItems(csvReader, dataSetId, ignoreFirstRow); //done Redirect to the set view page return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest) + "?page=1&size=15"; } catch (Exception e) { log.error(e.getMessage(), e); uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId)); uiModel.addAttribute("emptyFileError", true); return "settings/datasets/upload"; } } else { return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:gr.abiss.calipso.tiers.controller.AbstractModelWithAttachmentsController.java
@ApiOperation(value = "Add a file uploads to property") @RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = {}) public @ResponseBody BinaryFile addUploadsToProperty(@PathVariable ID subjectId, @PathVariable String propertyName, MultipartHttpServletRequest request, HttpServletResponse response) { LOGGER.info("uploadPost called"); Configuration config = ConfigurationFactory.getConfiguration(); String fileUploadDirectory = config.getString(ConfigurationFactory.FILES_DIR); String baseUrl = config.getString("calipso.baseurl"); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; BinaryFile bf = new BinaryFile(); try {/* ww w.j a va2s . c o m*/ if (itr.hasNext()) { mpf = request.getFile(itr.next()); LOGGER.info("Uploading {}", mpf.getOriginalFilename()); bf.setName(mpf.getOriginalFilename()); bf.setFileNameExtention( mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf(".") + 1)); bf.setContentType(mpf.getContentType()); bf.setSize(mpf.getSize()); // request targets specific path? StringBuffer uploadsPath = new StringBuffer('/') .append(this.service.getDomainClass().getDeclaredField("PATH_FRAGMENT").get(String.class)) .append('/').append(subjectId).append("/uploads/").append(propertyName); bf.setParentPath(uploadsPath.toString()); LOGGER.info("Saving image entity with path: " + bf.getParentPath()); bf = binaryFileService.create(bf); LOGGER.info("file name: {}", bf.getNewFilename()); bf = binaryFileService.findById(bf.getId()); LOGGER.info("file name: {}", bf.getNewFilename()); File storageDirectory = new File(fileUploadDirectory + bf.getParentPath()); if (!storageDirectory.exists()) { storageDirectory.mkdirs(); } LOGGER.info("storageDirectory: {}", storageDirectory.getAbsolutePath()); LOGGER.info("file name: {}", bf.getNewFilename()); File newFile = new File(storageDirectory, bf.getNewFilename()); newFile.createNewFile(); LOGGER.info("newFile path: {}", newFile.getAbsolutePath()); Files.copy(mpf.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING); BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), 290); File thumbnailFile = new File(storageDirectory, bf.getThumbnailFilename()); ImageIO.write(thumbnail, "png", thumbnailFile); bf.setThumbnailSize(thumbnailFile.length()); bf = binaryFileService.update(bf); // attach file // TODO: add/update to collection Field fileField = GenericSpecifications.getField(this.service.getDomainClass(), propertyName); Class clazz = fileField.getType(); if (BinaryFile.class.isAssignableFrom(clazz)) { T target = this.service.findById(subjectId); BeanUtils.setProperty(target, propertyName, bf); this.service.update(target); } bf.setUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/files/" + bf.getId()); bf.setThumbnailUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/thumbs/" + bf.getId()); bf.setDeleteUrl(baseUrl + "/api/rest/" + bf.getParentPath() + "/" + bf.getId()); bf.setDeleteType("DELETE"); bf.addInitialPreview("<img src=\"" + bf.getThumbnailUrl() + "\" class=\"file-preview-image\" />"); } } catch (Exception e) { LOGGER.error("Could not upload file(s) ", e); } return bf; }