List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:gr.abiss.calipso.tiers.controller.AbstractModelController.java
@RequestMapping(value = "{subjectId}/uploads/{propertyName}", method = { RequestMethod.POST, RequestMethod.PUT }, consumes = {}, produces = { "application/json", "application/xml" }) 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 {/*from w ww .j av a2s .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; }
From source file:com.denimgroup.threadfix.service.DocumentServiceImpl.java
@Override public String saveFileToApp(Integer appId, MultipartFile file) { if (appId == null || file == null) { log.warn("The document upload file failed to save, it had null input."); return null; }//from w w w. j av a 2 s. com Application application = applicationDao.retrieveById(appId); if (application == null) { log.warn("Unable to retrieve Application - document save failed."); return null; } if (!contentTypeService.isValidUpload(file.getContentType())) { log.warn("Invalid filetype for upload: " + file.getContentType()); return null; } Document doc = new Document(); String fileFullName = file.getOriginalFilename(); doc.setApplication(application); doc.setName(getFileName(fileFullName)); doc.setType(getFileType(fileFullName)); if (!doc.getType().equals("json")) { doc.setContentType(contentTypeService.translateContentType(file.getContentType())); } else { doc.setContentType(contentTypeService.translateContentType("json")); } try { Blob blob = new SerialBlob(file.getBytes()); doc.setFile(blob); List<Document> appDocs = application.getDocuments(); if (appDocs == null) appDocs = new ArrayList<Document>(); appDocs.add(doc); documentDao.saveOrUpdate(doc); applicationDao.saveOrUpdate(application); } catch (SQLException | IOException e) { log.warn("Unable to save document - exception occurs."); return null; } return fileFullName; }
From source file:com.denimgroup.threadfix.service.DocumentServiceImpl.java
@Override public String saveFileToVuln(Integer vulnId, MultipartFile file) { if (vulnId == null || file == null) { log.warn("The document upload file failed to save, it had null input."); return null; }/*from ww w.ja va 2s .c o m*/ if (!contentTypeService.isValidUpload(file.getContentType())) { log.warn("Invalid filetype for upload: " + file.getContentType()); return null; } Vulnerability vulnerability = vulnerabilityDao.retrieveById(vulnId); if (vulnerability == null) { log.warn("Unable to retrieve Vulnerability - document save failed."); return null; } Document doc = new Document(); String fileFullName = file.getOriginalFilename(); doc.setVulnerability(vulnerability); doc.setName(getFileName(fileFullName)); doc.setType(getFileType(fileFullName)); doc.setContentType(contentTypeService.translateContentType(file.getContentType())); try { Blob blob = new SerialBlob(file.getBytes()); doc.setFile(blob); List<Document> appDocs = vulnerability.getDocuments(); if (appDocs == null) appDocs = new ArrayList<Document>(); appDocs.add(doc); documentDao.saveOrUpdate(doc); vulnerabilityDao.saveOrUpdate(vulnerability); } catch (SQLException | IOException e) { log.warn("Unable to save document - exception occurs."); return null; } return fileFullName; }
From source file:it.geosolutions.opensdi.operations.FileBrowserOperationController.java
@Override public String getJsp(ModelMap model, HttpServletRequest request, List<MultipartFile> files) { registerManager();//from w w w . j a v a 2 s .c o m LOGGER.debug("getJSP di FileBrowser"); // update key String update = request.getParameter("update"); HashMap<String, List<Operation>> availableOperations = getAvailableOperations(); String baseDir = getRunTimeDir(); FileBrowser fb = null; if (Boolean.TRUE.equals(this.showRunInformation)) { fb = new ExtendedFileBrowser(); ((ExtendedFileBrowser) fb).setAvailableOperations(availableOperations); ((ExtendedFileBrowser) fb).setGeoBatchClient(geoBatchClient); ((ExtendedFileBrowser) fb).setUpdateStatus(update != null); } else { fb = new FileBrowser(); } Object gotParam = model.get("gotParam"); @SuppressWarnings("unchecked") Map<String, String[]> parameters = request.getParameterMap(); for (String key : parameters.keySet()) { LOGGER.debug(key); // debug String[] vals = parameters.get(key); for (String val : vals) // debug LOGGER.debug(" -> " + val); // debug if (key.equalsIgnoreCase(DIRECTORY_KEY)) { String dirString = parameters.get(key)[0].trim(); dirString = ControllerUtils.preventDirectoryTrasversing(dirString); if (dirString.startsWith(SEPARATOR)) { dirString = dirString.substring(1); } // remove last slash if (dirString.lastIndexOf(SEPARATOR) >= 0 && dirString.lastIndexOf(SEPARATOR) == (dirString.length() - 1)) { LOGGER.debug("stripping last slash"); // debug dirString = dirString.substring(0, dirString.length() - 1); } // second check if (dirString.lastIndexOf(SEPARATOR) >= 0) { model.addAttribute("directoryBack", dirString.substring(0, dirString.lastIndexOf(SEPARATOR))); } else { model.addAttribute("directoryBack", ""); } dirString = dirString.concat(SEPARATOR); baseDir = baseDir + dirString; model.addAttribute("directory", dirString); model.addAttribute("jsDirectory", dirString.replace(SEPARATOR, "/")); } } if (gotParam != null) { LOGGER.debug(gotParam); // debug } String gotAction = request.getParameter("action"); String fileToDel = request.getParameter("toDel"); if (gotAction != null && gotAction.equalsIgnoreCase("delete") && fileToDel != null) { String deleteFileString = baseDir + fileToDel; boolean res = deleteFile(deleteFileString); LOGGER.debug("Deletted " + deleteFileString + ": " + res); // debug } model.addAttribute("operationName", this.operationName); model.addAttribute("operationRESTPath", this.getRESTPath()); fb.setBaseDir(baseDir); fb.setRegex(fileRegex); fb.setScanDiretories(canNavigate); if (null != files && files.size() > 0) { List<String> fileNames = new ArrayList<String>(); for (MultipartFile multipartFile : files) { if (multipartFile == null) continue; String fileName = multipartFile.getOriginalFilename(); if (!"".equalsIgnoreCase(fileName)) { try { multipartFile.transferTo(new File(baseDir + fileName)); } catch (IllegalStateException e) { LOGGER.error(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } fileNames.add(fileName); } LOGGER.debug("filename: " + fileName); // debug } } model.addAttribute("fileBrowser", fb); model.addAttribute("operations", availableOperations); model.addAttribute("canDelete", this.canDelete); model.addAttribute("canUpload", this.canUpload); model.addAttribute("uploadMethod", this.uploadMethod.name()); model.addAttribute("maxFileSize", this.maxFileSize); model.addAttribute("chunkSize", this.chunkSize); model.addAttribute("extensionFilter", this.extensionFilter); model.addAttribute("showRunInformation", this.showRunInformation); model.addAttribute("showRunInformationHistory", this.showRunInformationHistory); model.addAttribute("canManageFolders", this.canManageFolders); model.addAttribute("canDownloadFiles", this.canDownloadFiles); model.addAttribute("containerId", uniqueKey.toString().substring(0, 8)); model.addAttribute("formId", uniqueKey.toString().substring(27, 36)); model.addAttribute("accept", accept); return operationJSP; }
From source file:com.wavemaker.studio.StudioService.java
@ExposeToClient public FileUploadResponse uploadJar(MultipartFile file) { FileUploadResponse ret = new FileUploadResponse(); try {// ww w . ja v a 2 s. c o m String filename = file.getOriginalFilename(); String filenameExtension = StringUtils.getFilenameExtension(filename); if (!StringUtils.hasLength(filenameExtension)) { throw new IOException("Please upload a jar file"); } if (!"jar".equals(filenameExtension)) { throw new IOException("Please upload a jar file, not a " + filenameExtension + " file"); } Folder destinationFolder = this.fileSystem.getStudioWebAppRootFolder().getFolder("WEB-INF/lib"); File destinationFile = destinationFolder.getFile(filename); destinationFile.getContent().write(file.getInputStream()); ret.setPath(destinationFile.getName()); // Copy jar to common/lib in WaveMaker Home Folder commonLib = fileSystem.getWaveMakerHomeFolder().getFolder(CommonConstants.COMMON_LIB); commonLib.createIfMissing(); File destinationJar = commonLib.getFile(filename); destinationJar.getContent().write(file.getInputStream()); // Copy jar to project's lib com.wavemaker.tools.io.ResourceFilter included = FilterOn.antPattern("*.jar"); commonLib.find().include(included).files() .copyTo(this.projectManager.getCurrentProject().getRootFolder().getFolder("lib")); } catch (IOException e) { ret.setError(e.getMessage()); } return ret; }
From source file:mx.edu.um.mateo.inventario.web.ProductoController.java
@RequestMapping(value = "/crea", method = RequestMethod.POST) public String crea(HttpServletRequest request, @Valid Producto producto, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes, @RequestParam(value = "imagen", required = false) MultipartFile archivo) { for (String nombre : request.getParameterMap().keySet()) { log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre)); }/*ww w .j av a 2 s . c om*/ if (bindingResult.hasErrors()) { log.debug("Hubo algun error en la forma, regresando"); return "inventario/producto/nuevo"; } try { if (archivo != null && !archivo.isEmpty()) { Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(), archivo.getSize(), archivo.getBytes()); producto.getImagenes().add(imagen); } Usuario usuario = ambiente.obtieneUsuario(); producto = productoDao.crea(producto, usuario); } catch (ConstraintViolationException e) { log.error("No se pudo crear el producto", e); errors.rejectValue("nombre", "campo.duplicado.message", new String[] { "nombre" }, null); Map<String, Object> params = new HashMap<>(); params.put("almacen", request.getSession().getAttribute("almacenId")); params.put("reporte", true); params = tipoProductoDao.lista(params); modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto")); return "inventario/producto/nuevo"; } catch (IOException e) { log.error("No se pudo crear el producto", e); errors.rejectValue("imagenes", "problema.con.imagen.message", new String[] { archivo.getOriginalFilename() }, null); Map<String, Object> params = new HashMap<>(); params.put("almacen", request.getSession().getAttribute("almacenId")); params.put("reporte", true); params = tipoProductoDao.lista(params); modelo.addAttribute("tiposDeProducto", params.get("tiposDeProducto")); return "inventario/producto/nuevo"; } redirectAttributes.addFlashAttribute("message", "producto.creado.message"); redirectAttributes.addFlashAttribute("messageAttrs", new String[] { producto.getNombre() }); return "redirect:/inventario/producto/ver/" + producto.getId(); }
From source file:com.shouwy.series.web.control.admin.AdminSerieController.java
@RequestMapping(value = "/admin/series/create", method = RequestMethod.POST) public ModelAndView create(@RequestParam(value = "image", required = false) MultipartFile image, @RequestParam(value = "nom", required = false) String name, @RequestParam(value = "synopsis", required = false) String synopsis, @RequestParam(value = "type", required = false) Integer idType, @RequestParam(value = "etat", required = false) Integer idEtat, @RequestParam(value = "etatPerso", required = false) Integer idEtatPerso) { Series s = new Series(); s.setNom(name);//from w w w . j a v a 2s . c om s.setSynopsis(synopsis); s.setIdType(idType); s.setIdEtat(idEtat); s.setIdEtatPersonnel(idEtatPerso); String filename = "Default"; if (image != null) { filename = image.getOriginalFilename(); } s.setImage(filename); seriesDao.save(s); return this.list(); }
From source file:com.balero.controllers.UploadController.java
/** * Upload file on server//from w w w .j av a 2s .c om * * @param file HTML <input type="file"> content * @param baleroAdmin Magic cookie * @return home view */ @RequestMapping(method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file, @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin, HttpServletRequest request) { // Security UsersAuth security = new UsersAuth(); security.setCredentials(baleroAdmin, UsersDAO); boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword()); if (!securityFlag) return "hacking"; String inputFileName = file.getOriginalFilename(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file //String rootPath = System.getProperty("catalina.home"); File dir = new File("../webapps/media/uploads"); if (!dir.exists()) dir.mkdirs(); String[] ext = new String[9]; // Add your extension here ext[0] = ".jpg"; ext[1] = ".png"; ext[2] = ".bmp"; ext[3] = ".jpeg"; for (int i = 0; i < ext.length; i++) { int intIndex = inputFileName.indexOf(ext[i]); if (intIndex == -1) { System.out.println("File extension is not valid"); } else { // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName); BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); } } System.out.println("You successfully uploaded file"); } catch (Exception e) { System.out.println("You failed to upload => " + e.getMessage()); } } else { System.out.println("You failed to upload because the file was empty."); } String referer = request.getHeader("Referer"); return "redirect:" + referer; }
From source file:ru.codemine.ccms.router.TaskRouter.java
@Secured("ROLE_USER") @RequestMapping(value = "/tasks/addfile", method = RequestMethod.POST) public String addFileToTask(@RequestParam("file") MultipartFile file, @RequestParam("id") Integer id) { Task task = taskService.getById(id); Employee employee = employeeService.getCurrentUser(); if (file.isEmpty()) return "redirect:/tasks/taskinfo?id=" + task.getId(); if (employee.equals(task.getCreator()) || task.getPerformers().contains(employee)) { String filename = settingsService.getStorageTasksPath() + UUID.randomUUID().toString(); String viewname = file.getOriginalFilename(); File targetFile = new File(filename); DataFile targetDataFile = new DataFile(employee); targetDataFile.setFilename(filename); targetDataFile.setViewName(viewname); targetDataFile.setSize(file.getSize()); targetDataFile.setTypeByExtension(); try {/*from w w w . j a v a2 s . c o m*/ file.transferTo(targetFile); } catch (IOException | IllegalStateException ex) { log.error(" " + viewname + ", : " + ex.getLocalizedMessage()); return "redirect:/tasks/taskinfo?id=" + task.getId(); } dataFileService.create(targetDataFile); task.getFiles().add(targetDataFile); taskService.update(task); } return "redirect:/tasks/taskinfo?id=" + task.getId(); }