List of usage examples for org.springframework.web.multipart MultipartFile transferTo
default void transferTo(Path dest) throws IOException, IllegalStateException
From source file:kr.co.exsoft.external.controller.ExternalPublicController.java
@RequestMapping(value = "/restful.multiUpload", method = RequestMethod.POST) @ResponseBody/*from ww w.j a va 2 s . co m*/ public String multiFileUploadTest(@ModelAttribute("uploadForm") ExternalMultiFileUpload uploadForm, Model map) throws IllegalStateException, IOException { String saveDirectory = "d:/temp/"; List<MultipartFile> crunchifyFiles = uploadForm.getFiles(); List<String> fileNames = new ArrayList<String>(); if (null != crunchifyFiles && crunchifyFiles.size() > 0) { for (MultipartFile multipartFile : crunchifyFiles) { String fileName = multipartFile.getOriginalFilename(); if (!"".equalsIgnoreCase(fileName)) { // Handle file content - multipartFile.getInputStream() multipartFile.transferTo(new File(saveDirectory + fileName)); fileNames.add(fileName); } } } else { return "File not found"; } map.addAttribute("files", fileNames); return "uploadfilesuccess"; }
From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java
@Override public void validateAndCopyFile(MultipartFile file, Integer projectId) throws IOException { String copyFolderPath = null; String projectPath = null;/*from w w w .j a va 2s . co m*/ boolean status = false; File tempFile = null; if (file.getOriginalFilename().toLowerCase().matches(".*\\.zip$|.*\\.xml$")) { copyFolderPath = Util.getPdiConfFolderPath(projectDetailsService.fetchProjectDetails(projectId)); projectPath = Util.getPdiConfDataFolderPath(projectDetailsService.fetchProjectDetails(projectId)); // if exists delete previously created folder deletePreviousUcsData(projectId); // create project folder Util.createFolder(projectPath); tempFile = new File(copyFolderPath + File.separator + file.getOriginalFilename()); file.transferTo(tempFile); if (tempFile.getName().toLowerCase().matches(".*\\.zip$") && validateZipFile(tempFile)) { copyZipFile(tempFile, projectPath); status = true; } else { copyXmlFile(tempFile, projectPath); status = true; } if (!status) { throw new FileExistsException(); } } }
From source file:com.pkrete.locationservice.admin.service.illustrations.ImagesServiceImpl.java
/** * Updates the given image object to the database and to the file system. * * @param image the image to be saved/* ww w .j ava2s . c o m*/ * @return true if and only if the image was successfully added; otherwise * false */ @Override public boolean update(Image image) { // Get JSON presentation String json = this.jsonizer.jsonize(image, true); // Get path of the images dir String path = Settings.getInstance().getImagesPath(image.getOwner().getCode()); // Get path of the images admin dir String adminPath = Settings.getInstance().getImagesPathAdmin(image.getOwner().getCode()); if (image.getFilePath() != null && image.getFilePath().length() > 0) { // Absolute source path String source = adminPath + image.getFilePath(); logger.debug("Move uploaded image file from admin dir to service dir."); // Check that the source file really exists if (!this.adminImageExists(image.getFilePath(), image.getOwner())) { logger.warn("Updating image failed, because the given file doesn't exist! Path : {}", source); return false; } // Absolute target path String target = path + image.getPath(); // If the image is external, name must be checked if (image.getIsExternal()) { // Old image was external, name of the image file must set String name = image.getFilePath(); // Name must be unique name = this.getUniqueName(path, name); // Set target path target = path + name; // Update path image.setPath(name); } logger.info("Move image file : \"{}\" -> \"{}\"", source, target); // Try to rename (=move) the file if (!fileService.replace(source, target)) { logger.warn("Moving image file failed! Updating image failed! Image : {}", json); return false; } // The image is not external image.setIsExternal(false); } else if (image.getUrl() != null && !image.getUrl().isEmpty()) { // If image is not external, the file must me deleted if (!image.getIsExternal()) { // Get path of the current file String target = IllustrationsUtil.buildFilePath(image); // Remove the file if (this.fileService.exists(target) && !this.fileService.delete(target)) { logger.warn( "Unable to delete the old image file while updating image from internal to external. Path : \"{}\"", target); logger.warn("Updating image failed! Image : {}", json); return false; } } // Update path image.setPath(image.getUrl()); // The image is external image.setIsExternal(true); } else if (image.getFile() != null && image.getFile().getSize() > 0) { // Check if user has uploaded a new image file logger.debug("Update image file."); // Get the uploaded file MultipartFile file = image.getFile(); // Absolute target path String target = path + image.getPath(); // Create a new File object for the uploaded file File imageFile = new File(target); // Delete the old image file, if file exists if (fileService.exists(target) && !fileService.delete(target)) { logger.warn("Updating image failed! Unable to delete the old image file. Path : \"{}\"", target); logger.warn("Updating image failed! Image : {}", json); return false; } logger.info("Write uploaded image file to disk. Path : \"{}\"", target); try { // Write the uploaded file to disk file.transferTo(imageFile); } catch (IOException ex) { logger.warn("Writing image file to disk failed!"); logger.error(ex.getMessage(), ex); logger.warn("Updating image failed! Image : {}", json); return false; } // Check that the file really exists if (!fileService.exists(target)) { logger.warn("Writing image file to disk failed! File doesn't exist. Path : \"{}\"", target); logger.warn("Updating image failed! Image : {}", json); return false; } } // Set updated date image.setUpdated(new Date()); // Try to update the DB if (dao.update(image)) { logger.info("Image updated : {}", this.jsonizer.jsonize(image, true)); return true; } logger.warn("Failed to update image : {}", json); return false; }
From source file:net.groupbuy.service.impl.FileServiceImpl.java
public String uploadLocal(FileType fileType, MultipartFile multipartFile) { if (multipartFile == null) { return null; }/*from w w w.j a v a 2s . c o m*/ Setting setting = SettingUtils.get(); String uploadPath; if (fileType == FileType.flash) { uploadPath = setting.getFlashUploadPath(); } else if (fileType == FileType.media) { uploadPath = setting.getMediaUploadPath(); } else if (fileType == FileType.file) { uploadPath = setting.getFileUploadPath(); } else { uploadPath = setting.getImageUploadPath(); } try { Map<String, Object> model = new HashMap<String, Object>(); model.put("uuid", UUID.randomUUID().toString()); String path = FreemarkerUtils.process(uploadPath, model); String destPath = path + UUID.randomUUID() + "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename()); File destFile = new File(servletContext.getRealPath(destPath)); if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } multipartFile.transferTo(destFile); return destPath; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.pkrete.locationservice.admin.service.illustrations.ImagesServiceImpl.java
/** * Saves the given file in the images directory of the Admin app. * * @param file file to be saved/*from w w w. j a va 2 s . co m*/ * @param owner owner of the file * @return name of the file if and only if the file was saved; otherwise * null */ @Override public String upload(MultipartFile file, Owner owner) { // Check for null values if (file == null || owner == null) { logger.warn("Writing image file to disk failed! File or owner can not be null."); return null; } // Get path of the images admin dir String path = Settings.getInstance().getImagesPathAdmin(owner.getCode()); // Get the name of the file String name = file.getOriginalFilename(); // Name must be unique name = this.getUniqueName(path, name); // Absolute target path path += name; // Create a new File object for the uploaded file File imageFile = new File(path); logger.info("Write uploaded image file to disk. Path : \"{}\"", path); try { // Write the uploaded file to disk file.transferTo(imageFile); } catch (IOException ex) { logger.warn("Writing image file to disk failed!"); logger.error(ex.getMessage(), ex); return null; } // Check that the file really exists if (!fileService.exists(path)) { logger.warn("Writing image file to disk failed! File doesn't exist. Path : \"{}\"", path); return null; } logger.info("Writing uploaded image file to disk done. Path : \"{}\"", path); return name; }
From source file:com.tssa.cooperationBusiness.controller.CooperationController.java
private String saveLogoFile(HttpServletRequest request) { String filePath = ""; try {/*from w w w .j a v a 2 s . c om*/ MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multiFile = multipartRequest.getFile("logoImageURL"); String cooperationId = request.getParameter("cooperationId"); // String fileUrl =request.getServletContext().getRealPath("/") + "upload/"; String viewUrl = request.getServletContext().getContextPath() + "/upload/"; // String fileUrl = "/Users/gmc/Works/eclipse/workspace/TSSA/WebContent/upload/"; File file = new File(fileUrl); if (!file.exists()) { file.mkdirs(); } if (multiFile != null && (multiFile.getOriginalFilename() != null && !"".equals(multiFile.getOriginalFilename()))) { File uploadFile = new File(fileUrl + cooperationId + multiFile.getOriginalFilename() .substring(multiFile.getOriginalFilename().lastIndexOf("."))); multiFile.transferTo(uploadFile); filePath = viewUrl + cooperationId + multiFile.getOriginalFilename() .substring(multiFile.getOriginalFilename().lastIndexOf(".")); return filePath; } else { return null; } } catch (IOException e) { LOG.error(e.getMessage(), e); return null; } }
From source file:fr.treeptik.cloudunit.controller.FileController.java
/** * Upload a file into a container/*from ww w . ja va 2 s . co m*/ * * @return * @throws IOException * @throws ServiceException * @throws CheckException */ @RequestMapping(value = "/container/{containerId}/application/{applicationName}/path/{path}", method = RequestMethod.POST, consumes = { "multipart/form-data" }) public @ResponseBody JsonResponse uploadFileToContainer(@RequestPart("file") MultipartFile fileUpload, @PathVariable final String containerId, @PathVariable final String applicationName, @PathVariable final String path, HttpServletRequest request, HttpServletResponse response) throws IOException, ServiceException, CheckException { if (logger.isDebugEnabled()) { logger.debug("-- CALL UPLOAD FILE TO CONTAINER FS --"); logger.debug("applicationName = " + applicationName); logger.debug("containerId = " + containerId); logger.debug("pathFile = " + path); } User user = authentificationUtils.getAuthentificatedUser(); Application application = applicationService.findByNameAndUser(user, applicationName); // We must be sure there is no running action before starting new one this.authentificationUtils.canStartNewAction(user, application, locale); // Application is now pending applicationService.setStatus(application, Status.PENDING); if (application != null) { File file = File.createTempFile("upload-", FilesUtils.setSuffix(fileUpload.getOriginalFilename())); fileUpload.transferTo(file); try { fileService.sendFileToContainer(applicationName, containerId, file, fileUpload.getOriginalFilename(), path); } catch (ServiceException e) { logger.error("Error during file upload : " + file); logger.error("containerId : " + containerId); logger.error("applicationName : " + applicationName); } finally { // in all case, the error during file upload cannot be critical. // We prefer to set the application in started mode applicationService.setStatus(application, Status.START); } } return new HttpOk(); }
From source file:com.hihsoft.baseclass.web.controller.javahihBaseController.java
/** * ?. ??BLOB?,.// w ww .j av a 2s . c om * ?,???,???,just for demo * * @param request * the request * @param uploadDir * the upload dir * @param parameterName * the parameter name * @return * @throws IOControllerException * Signals that an I/O ControllerException has occurred. */ protected String uploadImageToFile(final HttpServletRequest request, final String uploadDir, final String parameterName) throws IOException { String fileRelativePath = null; MultipartHttpServletRequest multipartRequest = null; try { multipartRequest = (MultipartHttpServletRequest) request; } catch (final ClassCastException e) { return null; // only for testcast ,mockservlet?MultipartRequest } final MultipartFile multipartFile = multipartRequest.getFile(parameterName); if (StringUtils.isNotEmpty(multipartFile.getOriginalFilename())) { final String fileName = multipartFile.getOriginalFilename(); final String fileRealPath = getServletContext().getRealPath(uploadDir) + File.separator + fileName; final File file = new File(fileRealPath); multipartFile.transferTo(file); fileRelativePath = uploadDir + "/" + fileName; } return fileRelativePath; }
From source file:com.mmj.app.biz.service.impl.FileServiceImpl.java
public Result createFilePath(MultipartFile file, IFileCreate... ihandle) { // ?/*from ww w . j ava2 s . c om*/ if (file == null) { return Result.failed(); } if (!file.isEmpty()) { if (StringUtils.isEmpty(file.getOriginalFilename())) { return Result.failed(); } String[] suffixArray = StringUtils.split(file.getOriginalFilename(), "."); if (Argument.isEmptyArray(suffixArray)) { return Result.failed(); } String prefix = null; if (Argument.isEmptyArray(ihandle)) { prefix = SerialNumGenerator.Random30String(); } else { prefix = ihandle[0].build(SerialNumGenerator.Random30String(), ""); } String suffix = null; if (suffixArray.length == 1) { suffix = "jpg"; } else { suffix = suffixArray[1]; } String filePath = prefix + DELIMITER + suffix; // String filePath48 = prefix + "=48x48" + DELIMITER + suffix; try { // file.transferTo(new File(UPLOAD_TMP_PATH + filePath)); // FileUtils.copyFile(new File(UPLOAD_TMP_PATH + filePath), new File(UPLOAD_TMP_PATH + filePath48)); return Result.success(null, STATIC_TMP_IMG + filePath); } catch (Exception e) { logger.error(e.getMessage()); return Result.failed(); } } return Result.failed(); }
From source file:com.i10n.fleet.web.controllers.DriverAdminOperations.java
@SuppressWarnings("rawtypes") public boolean Uploading(HttpServletRequest request) throws FileUploadException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { LOG.debug("File Not Uploaded"); } else {// ww w . j ava 2 s .co m Iterator fileNames = null; fileNames = ((MultipartHttpServletRequest) request).getFileNames(); MultipartFile file = null; if (fileNames.hasNext()) { String fileName = (String) fileNames.next(); file = ((MultipartHttpServletRequest) request).getFile(fileName); String itemName = null; try { itemName = file.getOriginalFilename(); } catch (Exception e) { LOG.error(e); } Random generator = new Random(); int r = Math.abs(generator.nextInt()); String reg = "[.*]"; String replacingtext = ""; Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(itemName); StringBuffer buffer = new StringBuffer(); while (matcher.find()) { matcher.appendReplacement(buffer, replacingtext); } int IndexOf = itemName.indexOf("."); String domainName = itemName.substring(IndexOf); finalimage = buffer.toString() + "_" + r + domainName; savedFile = new File("/usr/local/tomcat6/webapps/driverimage/" + finalimage); savedFile.getAbsolutePath(); try { file.transferTo(savedFile); /* * * transferTo uses the tranfering a file location to destination * */ } catch (IllegalStateException e1) { LOG.error(e1); } catch (IOException e1) { LOG.error(e1); } } } return true; }