List of usage examples for org.springframework.web.multipart MultipartFile isEmpty
boolean isEmpty();
From source file:com.linksinnovation.elearning.controller.api.UserController.java
@RequestMapping(value = "/user/avatar", method = RequestMethod.POST) public String avatarUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file, @AuthenticationPrincipal String user) throws Exception { if (!file.isEmpty()) { String fileName = user + "-" + name; byte[] bytes = file.getBytes(); try (BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File("/mnt/data/images/avatar/" + fileName)))) { stream.write(bytes);/*from w w w. j a v a2 s . c o m*/ } UserDetails userDetails = userDetailsRepository.findOne(user.toUpperCase()); userDetails.setAvatar(fileName); userDetailsRepository.save(userDetails); return fileName; } else { throw new Exception("You failed to upload because the file was empty."); } }
From source file:com.restfiddle.controller.rest.FileUploadController.java
@RequestMapping(value = "/api/import", method = RequestMethod.POST) public @ResponseBody void upload(@RequestParam("projectId") String projectId, @RequestParam("name") String name, @RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try {//from www .j a v a 2 s .co m byte[] bytes = file.getBytes(); String fileContent = new String(bytes); JSONObject pmCollection = new JSONObject(fileContent); String collectionName = pmCollection.getString("name"); System.out.println(collectionName); // Project project = projectController.findById(null, projectId); NodeDTO collectionNodeDTO = new NodeDTO(); collectionNodeDTO.setName(collectionName); collectionNodeDTO.setNodeType(NodeType.FOLDER.name()); collectionNodeDTO.setProjectId(projectId); NodeDTO collectionNode = nodeController.create(project.getProjectRef().getId(), collectionNodeDTO); JSONArray requests = pmCollection.getJSONArray("requests"); int len = requests.length(); for (int i = 0; i < len; i++) { JSONObject request = (JSONObject) requests.get(i); String requestName = request.getString("name"); String requestDescription = request.getString("description"); String requestUrl = request.getString("url"); String requestMethod = request.getString("method"); ConversationDTO conversationDTO = new ConversationDTO(); RfRequestDTO rfRequestDTO = new RfRequestDTO(); rfRequestDTO.setApiUrl(requestUrl); rfRequestDTO.setMethodType(requestMethod); String headersString = request.getString("headers"); if (headersString != null && !headersString.isEmpty()) { List<RfHeaderDTO> headerDTOs = new ArrayList<RfHeaderDTO>(); RfHeaderDTO headerDTO = null; String[] headersArr = headersString.split("\n"); for (String header : headersArr) { String[] headerToken = header.split(":"); String headerName = headerToken[0]; String headerValue = headerToken[1].trim(); headerDTO = new RfHeaderDTO(); headerDTO.setHeaderName(headerName); headerDTO.setHeaderValue(headerValue); headerDTOs.add(headerDTO); } rfRequestDTO.setHeaders(headerDTOs); } String dataMode = request.getString("dataMode"); if ("raw".equals(dataMode)) { String rawModeData = request.getString("rawModeData"); rfRequestDTO.setApiBody(rawModeData); } else if ("params".equals(dataMode)) { JSONArray formParamsArr = request.getJSONArray("data"); int arrLen = formParamsArr.length(); FormDataDTO formParam = null; List<FormDataDTO> formParams = new ArrayList<FormDataDTO>(); for (int j = 0; j < arrLen; j++) { JSONObject formParamJSON = (JSONObject) formParamsArr.get(j); formParam = new FormDataDTO(); formParam.setKey(formParamJSON.getString("key")); formParam.setValue(formParamJSON.getString("value")); formParams.add(formParam); } rfRequestDTO.setFormParams(formParams); } conversationDTO.setRfRequestDTO(rfRequestDTO); ConversationDTO createdConversation = conversationController.create(conversationDTO); conversationDTO.setId(createdConversation.getId()); // Request Node NodeDTO childNode = new NodeDTO(); childNode.setName(requestName); childNode.setDescription(requestDescription); childNode.setProjectId(projectId); childNode.setConversationDTO(conversationDTO); NodeDTO createdChildNode = nodeController.create(collectionNode.getId(), childNode); System.out.println("created node : " + createdChildNode.getName()); } } catch (Exception e) { logger.error(e.getMessage(), e); } } }
From source file:controllers.FeatureController.java
@RequestMapping("/updateFromXml") public String updateFromXml(Map<String, Object> model, @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) { if (file == null || file.isEmpty()) { ras.addFlashAttribute("error", "File not found"); } else {//from ww w .j a v a 2s. c om File newFile = new File("/usr/local/etc/Feature"); if (newFile.exists()) { newFile.delete(); } try { FileUtils.writeByteArrayToFile(newFile, file.getBytes()); featureService.updateFromXml(newFile); ras.addFlashAttribute("error", featureService.getResult().getErrors()); } catch (Exception e) { ras.addFlashAttribute("error", "updateFromXml " + StringAdapter.getStackTraceException(e)); } if (newFile.exists()) { newFile.delete(); } } return "redirect:/Feature/show"; }
From source file:com.orangeandbronze.jblubble.sample.PersonController.java
protected BlobKey createPhotoBlob(MultipartFile photoFile) { BlobKey blobKey = null;//from ww w . j a v a2s . c o m if (photoFile.isEmpty()) { blobKey = null; } else { try { InputStream inputStream = photoFile.getInputStream(); try { blobKey = blobstoreService.createBlob(inputStream, photoFile.getOriginalFilename(), photoFile.getContentType()); } finally { inputStream.close(); } } catch (Exception e) { logger.error("Error saving person's photo", e); } } return blobKey; }
From source file:ch.ralscha.extdirectspring_itest.FileUploadService.java
@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "itest_upload_service", event = "test", entryClass = String.class, synchronizeOnSession = true) public ExtDirectFormPostResult uploadTest(@RequestParam("fileUpload") MultipartFile file, @Valid User user, BindingResult result) throws IOException { ExtDirectFormPostResult resp = new ExtDirectFormPostResult(result, false); if (file != null && !file.isEmpty()) { resp.addResultProperty("fileContents", new String(file.getBytes())); resp.addResultProperty("fileName", file.getOriginalFilename()); }/*from w ww .j ava 2 s. co m*/ resp.addResultProperty("name", user.getName()); resp.addResultProperty("firstName", user.getFirstName()); resp.addResultProperty("age", user.getAge()); resp.addResultProperty("e-mail", user.getEmail()); resp.setSuccess(true); return resp; }
From source file:controllers.CarOptionValueController.java
@RequestMapping("/updateFromXml") public String updateFromXml(Map<String, Object> model, @RequestParam(value = "oldCcoId", required = false) Long oldCcoId, @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) throws Exception { if (file == null || file.isEmpty()) { ras.addFlashAttribute("error", "File not found"); } else {// w w w.j a v a 2 s. com File newFile = new File("/usr/local/etc/covs"); if (newFile.exists()) { newFile.delete(); } try { FileUtils.writeByteArrayToFile(newFile, file.getBytes()); carOptionValueService.updateFromXml(newFile); ras.addFlashAttribute("error", carOptionValueService.getResult().getErrors()); } catch (Exception e) { List<String> erList = new ArrayList(); erList.addAll(carOptionValueService.getResult().getErrors()); erList.add(e.getMessage()); ras.addFlashAttribute("error", "updateFromXml: " + /*StringAdapter.getStackTraceException(e)*/erList); } if (newFile.exists()) { newFile.delete(); } } ras.addAttribute("ccoId", oldCcoId); return "redirect:/CarOptionValue/show"; }
From source file:ch.ralscha.extdirectspring.provider.UploadService.java
@ExtDirectMethod(value = ExtDirectMethodType.FORM_POST, group = "group2", synchronizeOnSession = true) public ExtDirectFormPostResult upload(@RequestParam("fileUpload") MultipartFile file, @Valid User user, BindingResult result) throws IOException { ExtDirectFormPostResult resp = new ExtDirectFormPostResult(result, false); if (file != null && !file.isEmpty()) { resp.addResultProperty("fileContents", new String(file.getBytes())); resp.addResultProperty("fileName", file.getOriginalFilename()); }//from w ww .ja v a 2 s . c om resp.addResultProperty("name", user.getName()); resp.addResultProperty("firstName", user.getFirstName()); resp.addResultProperty("age", user.getAge()); resp.addResultProperty("e-mail", user.getEmail()); resp.setSuccess(true); return resp; }
From source file:com.mum.controller.ProductController.java
@RequestMapping(value = "products/add", method = RequestMethod.POST) public String processAddNewProductForm(@ModelAttribute("newProduct") Product product, BindingResult result, HttpServletRequest request, HttpServletResponse response) { MultipartFile productImage = product.getProductImage(); String rootDirectory = request.getSession().getServletContext().getRealPath("/../../../"); if (productImage != null && !productImage.isEmpty()) { try {//from w w w .j av a 2s. c o m productImage.transferTo( new File(rootDirectory + "\\images\\" + productImage.getOriginalFilename() + ".png")); } catch (Exception e) { throw new RuntimeException("Product Image saving failed", e); } } String[] suppressedFields = result.getSuppressedFields(); if (suppressedFields.length > 0) { throw new RuntimeException("Attempting to bind disallowed fields:" + StringUtils.arrayToCommaDelimitedString(suppressedFields)); } productService.addProduct(product); //return "redirect:/products/add"; //return "redirect:/products"; return ""; }
From source file:fr.xebia.cocktail.CocktailManager.java
/** * TODO use PUT instead of POST/*from w w w .j a v a 2s .c o m*/ * * @param id id of the cocktail * @param photo to associate with the cocktail * @return redirection to display cocktail */ @RequestMapping(value = "/cocktail/{id}/photo", method = RequestMethod.POST) public String updatePhoto(@PathVariable String id, @RequestParam("photo") MultipartFile photo) { if (!photo.isEmpty()) { try { String contentType = fileStorageService.findContentType(photo.getOriginalFilename()); if (contentType == null) { logger.warn("photo", "Skip file with unsupported extension '" + photo.getOriginalFilename() + "'"); } else { InputStream photoInputStream = photo.getInputStream(); long photoSize = photo.getSize(); Map metadata = new TreeMap(); metadata.put("Content-Length", Arrays.asList(new String[] { "" + photoSize })); metadata.put("Content-Type", Arrays.asList(new String[] { contentType })); metadata.put("Cache-Control", Arrays.asList( new String[] { "public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS) })); /* ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(photoSize); objectMetadata.setContentType(contentType); objectMetadata.setCacheControl("public, max-age=" + TimeUnit.SECONDS.convert(365, TimeUnit.DAYS));*/ String photoUrl = fileStorageService.storeFile(photo.getBytes(), metadata); Cocktail cocktail = cocktailRepository.get(id); logger.info("Saved {}", photoUrl); cocktail.setPhotoUrl(photoUrl); cocktailRepository.update(cocktail); } } catch (IOException e) { throw Throwables.propagate(e); } } return "redirect:/cocktail/" + id; }
From source file:controllers.PropertyController.java
@RequestMapping("/updateFromXml") public String updateFromXml(Map<String, Object> model, @RequestParam(value = "propId", required = true) Long propId, @RequestParam(value = "xlsFile", required = false) MultipartFile file, RedirectAttributes ras) throws Exception { if (file == null || file.isEmpty()) { ras.addFlashAttribute("error", "File not found"); } else {/*w ww.j ava 2s. c o m*/ File newFile = new File("/usr/local/etc/Properties"); if (newFile.exists()) { newFile.delete(); } try { FileUtils.writeByteArrayToFile(newFile, file.getBytes()); propertyNameService.updateFromXml(newFile); ras.addFlashAttribute("error", propertyNameService.getResult().getErrors()); } catch (Exception e) { //ras.addFlashAttribute("error", "updateFromXml"+e.getMessage()); throw new Exception(StringAdapter.getStackTraceException(e)); } if (newFile.exists()) { newFile.delete(); } } ras.addAttribute("propId", propId); return "redirect:/PropertyName/show"; }