List of usage examples for org.springframework.web.multipart MultipartHttpServletRequest getParameter
public String getParameter(String name);
String
, or null
if the parameter does not exist. From source file:org.kuali.rice.krad.web.service.impl.FileControllerServiceImpl.java
/** * {@inheritDoc}/* ww w . j av a 2 s.c o m*/ */ @Override public ModelAndView addFileUploadLine(final UifFormBase form) { form.setAjaxReturnType(UifConstants.AjaxReturnTypes.UPDATECOMPONENT.getKey()); form.setAjaxRequest(true); MultipartHttpServletRequest request = (MultipartHttpServletRequest) form.getRequest(); final String collectionId = request.getParameter(UifParameters.UPDATE_COMPONENT_ID); final String bindingPath = request.getParameter(UifConstants.PostMetadata.BINDING_PATH); Class<?> collectionObjectClass = (Class<?>) form.getViewPostMetadata().getComponentPostData(collectionId, UifConstants.PostMetadata.COLL_OBJECT_CLASS); Iterator<String> fileNamesItr = request.getFileNames(); while (fileNamesItr.hasNext()) { String propertyPath = fileNamesItr.next(); MultipartFile uploadedFile = request.getFile(propertyPath); final FileMeta fileObject = (FileMeta) KRADUtils.createNewObjectFromClass(collectionObjectClass); try { fileObject.init(uploadedFile); } catch (Exception e) { throw new RuntimeException("Unable to initialize new file object", e); } String id = UUID.randomUUID().toString() + "_" + uploadedFile.getName(); fileObject.setId(id); fileObject.setDateUploaded(new Date()); fileObject.setUrl("?methodToCall=getFileFromLine&formKey=" + form.getFormKey() + "&fileName=" + fileObject.getName() + "&propertyPath=" + propertyPath); ViewLifecycle.encapsulateLifecycle(form.getView(), form, form.getViewPostMetadata(), null, request, new Runnable() { @Override public void run() { ViewLifecycle.getHelper().processAndAddLineObject(form, fileObject, collectionId, bindingPath); } }); } return getModelAndViewService().getModelAndView(form); }
From source file:org.mitre.mpf.mvc.controller.MediaController.java
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST) public ResponseEntity saveMediaFileUpload(MultipartHttpServletRequest request, HttpServletResponse response) throws WfmProcessingException, MpfServiceException { log.debug("[saveMediaFileUpload]"); File newFile = null;//from w w w .jav a 2s.co m String desiredPathParam = request.getParameter("desiredpath"); log.debug("Upload to Directory:" + desiredPathParam); if (desiredPathParam == null) return new ResponseEntity<>("{\"error\":\"desiredPathParam Empty\"}", HttpStatus.INTERNAL_SERVER_ERROR); String webTmpDirectory = propertiesUtil.getRemoteMediaCacheDirectory().getAbsolutePath(); try { //verify the desired path File desiredPath = new File(desiredPathParam); if (!desiredPath.exists() || !desiredPath.getAbsolutePath().startsWith(webTmpDirectory)) {//make sure it is valid and within the remote-media directory String err = "Error with desired path: " + desiredPathParam; log.error(err); return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR); } Iterator<String> itr = request.getFileNames(); while (itr.hasNext()) { String uploadedFile = itr.next(); MultipartFile file = request.getFile(uploadedFile); String filename = file.getOriginalFilename(); byte[] bytes = file.getBytes(); String contentType = ioUtils.getMimeType(bytes); log.debug("[saveMediaFileUpload] File:" + filename + " ContentType:" + contentType + " Size:" + bytes.length); if (filename.isEmpty()) { String err = "The filename is empty during upload of the MultipartFile."; log.error(err); return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR); } //return error if the file has an invalid content type and the filename does not have a valid extension if (!ioUtils.isApprovedFile(contentType, filename)) { String msg = "The media is not a supported type. Please add a whitelist." + contentType + " entry to the mediaType.properties file."; log.error(msg + " File:" + filename); return new ResponseEntity<>("{\"error\":\"" + msg + "\"}", HttpStatus.INTERNAL_SERVER_ERROR); } //get a new filename newFile = ioUtils.getNewFileName(desiredPath.getAbsolutePath(), filename); //save the file BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(newFile)); stream.write(bytes); stream.close(); log.info("Completed upload and write of {} to {} ContentType:{}", newFile.getPath(), newFile.getAbsolutePath(), contentType); return new ResponseEntity<>(filename, HttpStatus.OK); } } catch (IOException badWrite) { String err = "Error writing media to temp file"; log.error(err); return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR); } catch (Exception e) { String err = "Unknown file upload error"; log.error(err, e); return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR); } String err = "Unknown file upload error"; log.error(err); return new ResponseEntity<>("{\"error\":\"" + err + "\"}", HttpStatus.INTERNAL_SERVER_ERROR); }
From source file:org.sakaiproject.gradebook.gwt.sakai.GradebookImportController.java
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; String gradebookUid = multipartRequest.getParameter(AppConstants.REQUEST_FORM_FIELD_GBUID); String justStructureCheckBox = multipartRequest.getParameter(AppConstants.IMPORT_PARAM_STRUCTURE); Boolean importJustStructure = justStructureCheckBox != null; String fileTypeNameFromClient = multipartRequest .getParameter(AppConstants.IMPORT_PARAM_FILETYPE + "-hidden"); String fileFormatChosen = multipartRequest.getParameter(AppConstants.IMPORT_PARAM_FILEFORMAT + "-hidden"); FileFormat fileFormatFromClient = FileFormat.getFormatByName(fileFormatChosen); ImportSettings importSettings = new ImportSettingsImpl(); importSettings.setJustStructure(importJustStructure); importSettings.setGradebookUid(gradebookUid); for (Iterator<String> fileNameIterator = multipartRequest.getFileNames(); fileNameIterator.hasNext();) { String fileName = fileNameIterator.next(); MultipartFile file = multipartRequest.getFile(fileName); String origName = file.getOriginalFilename(); Upload importFile = null;/*from w w w .ja v a 2s.com*/ // first check for sane choices on the client side FileType fileTypeFromFileExt = null; if (fileFormatFromClient == null) { importFile = new UploadImpl(); importFile.setNotes(i18n.getString("unknownFormatSelected")); importFile.setErrors(true); } else { int theLastDot = origName.lastIndexOf("."); if (theLastDot > 0) { fileTypeFromFileExt = FileType.getTypeFromExtension(origName.substring(theLastDot)); if (!fileTypeFromFileExt.equals(FileType.valueOf(fileTypeNameFromClient))) { importFile = new UploadImpl(); importFile.setNotes(i18n.getString("filetypeExtensionMismatch") + fileTypeNameFromClient); importFile.setErrors(true); } } else {//client should be preventing this as of SAK-1221 importFile = new UploadImpl(); importFile.setNotes(i18n.getString("noFileExtensionFound")); importFile.setErrors(true); } } log.debug("Original Name: " + origName + "; type: " + fileTypeFromFileExt); if ((importFile == null || !importFile.hasErrors()) && fileTypeFromFileExt != null) { importSettings.setExportTypeName((ExportType.valueOf(fileTypeNameFromClient)).name()); importSettings.setFileFormatName(fileFormatFromClient.name()); importFile = importExportUtility.getImportFile(file, importSettings); } PrintWriter writer = response.getWriter(); response.setContentType(CONTENT_TYPE_TEXT_HTML); // NOTE: Only use this during DEV phase //saveJsonToFile(importFile, "/tmp/data.json"); if (null == importFile) { importFile = new UploadImpl(); importFile.setErrors(true); importFile.setNotes(i18n.getString("unknownFileType")); } else if (!importJustStructure) { /// to save a few cycles //GRBK-1194 List<Learner> rows = importFile.getRows(); List<String> studentIds = new ArrayList<String>(); StringBuffer msg = null; boolean dupsFound = false; if (rows != null) { for (Learner student : rows) { String id = student.getIdentifier(); if (null == id) continue; if (studentIds.contains(id) && !student.getUserNotFound()) { dupsFound = true; if (null == msg) { msg = new StringBuffer(i18n.getString("importDuplicateStudentsFound", "Duplicate rows found in the table. The following Student Id's where duplicated: ")) .append("'").append(student.getStudentName()).append("'"); } else { msg.append(",").append("'").append(student.getStudentName()).append("'"); } } else { studentIds.add(id); } } if (dupsFound) { importFile.setErrors(true); importFile.setNotes(msg.toString()); } } } writer.write(SafeHtmlUtils.htmlEscape(toJson(importFile))); writer.flush(); writer.close(); } return null; }
From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java
private void doTestParameters(MultipartHttpServletRequest request) { Set<String> parameterNames = new HashSet<>(); Enumeration<String> parameterEnum = request.getParameterNames(); while (parameterEnum.hasMoreElements()) { parameterNames.add(parameterEnum.nextElement()); }/* w w w . ja v a2 s .c o m*/ assertEquals(3, parameterNames.size()); assertTrue(parameterNames.contains("field3")); assertTrue(parameterNames.contains("field4")); assertTrue(parameterNames.contains("getField")); assertEquals("value3", request.getParameter("field3")); List<String> parameterValues = Arrays.asList(request.getParameterValues("field3")); assertEquals(1, parameterValues.size()); assertTrue(parameterValues.contains("value3")); assertEquals("value4", request.getParameter("field4")); parameterValues = Arrays.asList(request.getParameterValues("field4")); assertEquals(2, parameterValues.size()); assertTrue(parameterValues.contains("value4")); assertTrue(parameterValues.contains("value5")); assertEquals("value4", request.getParameter("field4")); assertEquals("getValue", request.getParameter("getField")); List<String> parameterMapKeys = new ArrayList<>(); List<Object> parameterMapValues = new ArrayList<>(); for (Object o : request.getParameterMap().keySet()) { String key = (String) o; parameterMapKeys.add(key); parameterMapValues.add(request.getParameterMap().get(key)); } assertEquals(3, parameterMapKeys.size()); assertEquals(3, parameterMapValues.size()); int field3Index = parameterMapKeys.indexOf("field3"); int field4Index = parameterMapKeys.indexOf("field4"); int getFieldIndex = parameterMapKeys.indexOf("getField"); assertTrue(field3Index != -1); assertTrue(field4Index != -1); assertTrue(getFieldIndex != -1); parameterValues = Arrays.asList((String[]) parameterMapValues.get(field3Index)); assertEquals(1, parameterValues.size()); assertTrue(parameterValues.contains("value3")); parameterValues = Arrays.asList((String[]) parameterMapValues.get(field4Index)); assertEquals(2, parameterValues.size()); assertTrue(parameterValues.contains("value4")); assertTrue(parameterValues.contains("value5")); parameterValues = Arrays.asList((String[]) parameterMapValues.get(getFieldIndex)); assertEquals(1, parameterValues.size()); assertTrue(parameterValues.contains("getValue")); }