List of usage examples for org.springframework.web.multipart MultipartFile transferTo
default void transferTo(Path dest) throws IOException, IllegalStateException
From source file:org.gallery.web.controller.FileController.java
@RequestMapping(value = "/uploadfile", method = RequestMethod.POST) public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) { log.info("uploadfile called..."); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<DataFileEntity> list = new LinkedList<>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); String originalFilename = mpf.getOriginalFilename(); log.info("Uploading {}", originalFilename); String key = UUID.randomUUID().toString(); String storageDirectory = fileUploadDirectory; File file = new File(storageDirectory + File.separatorChar + key); try {/*from www .j a v a 2 s .c o m*/ // Save Images mpf.transferTo(file); // Save FileEntity DataFileEntity dataFileEntity = new DataFileEntity(); dataFileEntity.setName(mpf.getOriginalFilename()); dataFileEntity.setKey(key); dataFileEntity.setSize(mpf.getSize()); dataFileEntity.setContentType(mpf.getContentType()); dataFileDao.save(dataFileEntity); list.add(dataFileEntity); } catch (IOException e) { log.error("Could not upload file " + originalFilename, e); } } Map<String, Object> files = new HashMap<>(); files.put("files", list); return files; }
From source file:csns.util.FileIO.java
public File save(MultipartFile uploadedFile, User user, File parent, boolean isPublic) { if (uploadedFile.isEmpty()) return null; File file = new File(); file.setName(uploadedFile.getOriginalFilename()); file.setType(uploadedFile.getContentType()); file.setSize(uploadedFile.getSize()); file.setOwner(user);/*from ww w .j a v a2 s . c o m*/ file.setParent(parent); file.setPublic(isPublic); file = fileDao.saveFile(file); java.io.File diskFile = getDiskFile(file, false); try { uploadedFile.transferTo(diskFile); } catch (Exception e) { logger.error("Failed to save uploaded file", e); } return file; }
From source file:com.mycompany.rent.controllers.ListingController.java
@RequestMapping(value = "/photo/{id}", method = RequestMethod.POST) public String addPhotos(@RequestParam("file") MultipartFile file, @PathVariable int id, Map model) throws IOException { if (!file.isEmpty()) { ForRent rent = forRentDao.get(id); String realPathtoUploads = "/home/brennan/_repos/rent/src/main/webapp/uploads/" + id; String orgName = file.getOriginalFilename(); rent.setFileName(orgName);//from w w w .j a v a 2s .com forRentDao.addPhotos(id, orgName); String filePath = (realPathtoUploads + rent.getId() + "_" + orgName); File dest = new File(filePath); file.transferTo(dest); return "home"; } return "home"; }
From source file:fr.treeptik.cloudunit.manager.impl.ApplicationManagerImpl.java
/** * Deployment for an archive/* w ww . java 2 s . co m*/ * * @param fileUpload * @param application */ public void deploy(MultipartFile fileUpload, Application application) throws ServiceException, CheckException { try { logger.debug(application.toString()); // Deployment processus with verification for format file if (FilesUtils.isAuthorizedFileForDeployment(fileUpload.getOriginalFilename())) { File file = File.createTempFile("deployment-", FilesUtils.setSuffix(fileUpload.getOriginalFilename())); fileUpload.transferTo(file); if (application.getStatus().equals(Status.STOP)) { throw new CheckException(messageSource.getMessage("app.stop", null, Locale.ENGLISH)); } // Application busy applicationService.setStatus(application, Status.PENDING); // Deployment applicationService.deploy(file, application); // application is started applicationService.setStatus(application, Status.START); } else { throw new CheckException(messageSource.getMessage("check.war.ear", null, Locale.ENGLISH)); } } catch (IOException e) { applicationService.setStatus(application, Status.FAIL); throw new ServiceException(e.getMessage()); } }
From source file:org.sakaiproject.mailsender.tool.beans.EmailBean.java
public String sendEmail() { // make sure we have a minimum of data required if (emailEntry == null || emailEntry.getConfig() == null) { messages.addMessage(new TargettedMessage("error.nothing.send")); return EMAIL_FAILED; }/*w w w. java 2 s .co m*/ ConfigEntry config = emailEntry.getConfig(); User curUser = externalLogic.getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayName(); } if (fromEmail == null || fromEmail.trim().length() == 0) { messages.addMessage(new TargettedMessage("no.from.address")); return EMAIL_FAILED; } HashMap<String, String> emailusers = new HashMap<String, String>(); // compile the list of emails to send to compileEmailList(fromEmail, emailusers); // handle the other recipients List<String> emailOthers = emailEntry.getOtherRecipients(); String[] allowedDomains = StringUtil.split(configService.getString("sakai.mailsender.other.domains"), ","); List<String> invalids = new ArrayList<String>(); // add other recipients to the message for (String email : emailOthers) { if (allowedDomains != null && allowedDomains.length > 0) { // check each "other" email to ensure it ends with an accepts domain for (String domain : allowedDomains) { if (email.endsWith(domain)) { emailusers.put(email, null); } else { invalids.add(email); } } } else { emailusers.put(email, null); } } String content = emailEntry.getContent(); if (emailEntry.getConfig().isAppendRecipientList()) { content = content + compileRecipientList(emailusers); } String subjectContent = emailEntry.getSubject(); if (subjectContent == null || subjectContent.trim().length() == 0) { subjectContent = messageLocator.getMessage("no.subject"); } String subject = ((config.getSubjectPrefix() != null) ? config.getSubjectPrefix() : "") + subjectContent; try { if (invalids.size() == 0) { List<Attachment> attachments = new ArrayList<Attachment>(); if (multipartMap != null && !multipartMap.isEmpty()) { for (Entry<String, MultipartFile> entry : multipartMap.entrySet()) { MultipartFile mf = entry.getValue(); String filename = mf.getOriginalFilename(); try { File f = File.createTempFile(filename, null); mf.transferTo(f); Attachment attachment = new Attachment(f, filename); attachments.add(attachment); } catch (IOException ioe) { throw new AttachmentException(ioe.getMessage()); } } } // send the message invalids = externalLogic.sendEmail(config, fromEmail, fromDisplay, emailusers, subject, content, attachments); } // append to the email archive String siteId = externalLogic.getSiteID(); String fromString = fromDisplay + " <" + fromEmail + ">"; addToArchive(config, fromString, subject, siteId); // build output message for results screen for (Entry<String, String> entry : emailusers.entrySet()) { String compareAddr = null; String addrStr = null; if (entry.getValue() != null && entry.getValue().trim().length() > 0) { addrStr = entry.getValue(); compareAddr = "\"" + entry.getValue() + "\" <" + entry.getKey() + ">"; } else { addrStr = entry.getKey(); compareAddr = entry.getKey(); } if (!invalids.contains(compareAddr)) { messages.addMessage(new TargettedMessage("verbatim", new String[] { addrStr }, TargettedMessage.SEVERITY_CONFIRM)); } } } catch (MailsenderException me) { //Print this exception log.warn(me); messages.clear(); List<Map<String, Object[]>> msgs = me.getMessages(); if (msgs != null) { for (Map<String, Object[]> msg : msgs) { for (Map.Entry<String, Object[]> e : msg.entrySet()) { messages.addMessage( new TargettedMessage(e.getKey(), e.getValue(), TargettedMessage.SEVERITY_ERROR)); } } } else { messages.addMessage(new TargettedMessage("verbatim", new String[] { me.getMessage() }, TargettedMessage.SEVERITY_ERROR)); } return EMAIL_FAILED; } catch (AttachmentException ae) { messages.clear(); messages.addMessage(new TargettedMessage("error.attachment", new String[] { ae.getMessage() }, TargettedMessage.SEVERITY_ERROR)); return EMAIL_FAILED; } // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = config.isDisplayInvalidEmails(); if (showBadEmails && invalids != null && invalids.size() > 0) { // add the message for the result screen String names = invalids.toString(); messages.addMessage(new TargettedMessage("invalid.email.addresses", new String[] { names.substring(1, names.length() - 1) }, TargettedMessage.SEVERITY_INFO)); } return EMAIL_SENT; }
From source file:com.ylife.goods.model.UploadImgUpyun.java
/** * ????/*w w w.j av a 2s .c om*/ * * @param muFile * @return Map?oldimgsmall? */ public Map<String, String> testUpYun(MultipartFile muFile, UpyunConf upConf) throws IOException { Map<String, String> imgMap = new HashMap<String, String>(); if (muFile != null && muFile.getSize() != 0) { // ??????????? String fileNamess = UploadImgCommon.getPicNamePathSuffix(); File file = new File(fileNamess); muFile.transferTo(file); if (upConf != null) { YunBean yb = new YunBean(); yb.setBucketName(upConf.getBucketName()); yb.setPassword(upConf.getPassWord()); yb.setUserName(upConf.getUserName()); KUpYunUtil.kYunUp(fileNamess, UploadImgCommon.prefix, yb, UploadImgCommon.suffix); // ?? //LOGGER.debug(LOGGERINFO1 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix); imgMap.put(OLDIMG, upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix); // ?? int[] widths = UploadImgCommon.getImgSet(imageSetMapper.queryImageSet()); UploadImgCommon.sortWidth(widths); for (int i = 0; i < widths.length; i++) { // ?? //LOGGER.debug(LOGGERINFO2 + widths[i] + LOGGERINFO3 + upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]); imgMap.put(widths[i] + "", upConf.getUrlPath() + UploadImgCommon.prefix + UploadImgCommon.suffix + "!" + widths[i]); } } return imgMap; } else { return null; } }
From source file:jetbrains.buildServer.clouds.azure.web.AzureEditProfileController.java
public AzureEditProfileController(@NotNull final SBuildServer server, @NotNull final PluginDescriptor pluginDescriptor, @NotNull final WebControllerManager manager) { super(server); myPluginDescriptor = pluginDescriptor; myHtmlPath = pluginDescriptor.getPluginResourcesPath("azure-settings.html"); myJspPath = pluginDescriptor.getPluginResourcesPath("azure-settings.jsp"); manager.registerController(myHtmlPath, this); manager.registerController(pluginDescriptor.getPluginResourcesPath("uploadManagementCertificate.html"), new MultipartFormController() { @Override//ww w. j a v a 2 s. com protected ModelAndView doPost(final HttpServletRequest request, final HttpServletResponse response) { final ModelAndView modelAndView = new ModelAndView("/_fileUploadResponse.jsp"); final String fileName = request.getParameter("fileName"); boolean exists; try { final MultipartFile file = getMultipartFileOrFail(request, "file:fileToUpload"); if (file == null) { return error(modelAndView, "No file set"); } final File pluginDataDirectory = FileUtil.createDir(new File("")); final File destinationFile = new File(pluginDataDirectory, fileName); exists = destinationFile.exists(); file.transferTo(destinationFile); } catch (IOException e) { return error(modelAndView, e.getMessage()); } catch (IllegalStateException e) { return error(modelAndView, e.getMessage()); } if (exists) { Loggers.SERVER.info("File " + fileName + " is overwritten"); ActionMessages.getOrCreateMessages(request).addMessage("mavenSettingsUploaded", "Maven settings file " + fileName + " was updated"); } else { ActionMessages.getOrCreateMessages(request).addMessage("mavenSettingsUploaded", "Maven settings file " + fileName + " was uploaded"); } return modelAndView; } protected ModelAndView error(@NotNull ModelAndView modelAndView, @NotNull String error) { modelAndView.getModel().put("error", error); return modelAndView; } }); }
From source file:controllers.ProcessController.java
@RequestMapping("management/staffs/edit") public ModelAndView editStaff(@RequestParam("id") String id, @RequestParam("name") String name, @RequestParam("gender") String genderString, @RequestParam("birthday") String birthdayString, @RequestParam("avatar") MultipartFile avatar, @RequestParam("email") String email, @RequestParam("phone") String phone, @RequestParam("salary") String salaryString, @RequestParam("note") String notes, @RequestParam("depart") String departId) throws IOException { String avatarFileName = ""; if (!avatar.isEmpty()) { String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename()); avatar.transferTo(new File(avatarPath)); avatarFileName = new File(avatarPath).getName(); }/*from ww w .j ava 2s. c om*/ StaffsDAO staffsDAO = new StaffsDAO(); staffsDAO.editStaff(id, name, genderString, birthdayString, avatarFileName, email, phone, salaryString, notes, departId); return new ModelAndView("redirect:../staffs.htm"); }
From source file:com.xx.backend.controller.EmployeeController.java
@RequestMapping(value = "/form_upload2.html") public @ResponseBody String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) { System.out.println(""); String path = request.getSession().getServletContext().getRealPath("upload"); String fileName = file.getOriginalFilename(); // String fileName = new Date().getTime()+".jpg"; System.out.println(path);//w ww . ja v a2 s . co m File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } //? try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName); Map paramsMap = new QMap(200); return JSONObject.toJSONString(paramsMap); }
From source file:org.openmrs.module.sdmxhdintegration.web.controller.MessageUploadFormController.java
/** * Handles form submission/*from w w w . j a va 2s .com*/ * @param request the request * @param message the message * @param result the binding result * @param status the session status * @return the view * @throws IllegalStateException */ @RequestMapping(method = RequestMethod.POST) public String handleSubmission(HttpServletRequest request, @ModelAttribute("message") SDMXHDMessage message, BindingResult result, SessionStatus status) throws IllegalStateException { DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request; MultipartFile file = req.getFile("sdmxhdMessage"); File destFile = null; if (!(file.getSize() <= 0)) { AdministrationService as = Context.getAdministrationService(); String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir"); String filename = file.getOriginalFilename(); filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename; destFile = new File(dir + File.separator + filename); destFile.mkdirs(); try { file.transferTo(destFile); } catch (IOException e) { HttpSession session = request.getSession(); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user."); return "/module/sdmxhdintegration/messageUpload"; } message.setZipFilename(filename); } new SDMXHDMessageValidator().validate(message, result); if (result.hasErrors()) { log.error("SDMXHDMessage object failed validation"); if (destFile != null) { destFile.delete(); } return "/module/sdmxhdintegration/messageUpload"; } SDMXHDService service = Context.getService(SDMXHDService.class); ReportDefinitionService rds = Context.getService(ReportDefinitionService.class); service.saveMessage(message); // delete all existing mappings and reports List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = service.getKeyFamilyMappingsFromMessage(message); for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) { KeyFamilyMapping kfm = iterator.next(); Integer reportDefinitionId = kfm.getReportDefinitionId(); service.deleteKeyFamilyMapping(kfm); if (reportDefinitionId != null) { rds.purgeDefinition(rds.getDefinition(reportDefinitionId)); } } // create initial keyFamilyMappings try { DSD dsd = Utils.getDataSetDefinition(message); List<KeyFamily> keyFamilies = dsd.getKeyFamilies(); for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) { KeyFamily keyFamily = iterator.next(); KeyFamilyMapping kfm = new KeyFamilyMapping(); kfm.setKeyFamilyId(keyFamily.getId()); kfm.setMessage(message); service.saveKeyFamilyMapping(kfm); } } catch (Exception e) { log.error("Error parsing SDMX-HD Message: " + e, e); if (destFile != null) { destFile.delete(); } service.deleteMessage(message); result.rejectValue("sdmxhdZipFileName", "upload.file.rejected", "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition"); return "/module/sdmxhdintegration/messageUpload"; } return "redirect:messages.list"; }