List of usage examples for org.springframework.web.multipart MultipartFile transferTo
default void transferTo(Path dest) throws IOException, IllegalStateException
From source file:no.dusken.aranea.admin.control.UploadFileController.java
@Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object object, BindException bindException) throws Exception { String url = ServletRequestUtils.getRequiredStringParameter(request, "imageUrl"); // get the uploaded file MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("file"); if (file == null) { // There is no file. Exit log.error("Could not extract file from request"); return new ModelAndView(new EmptyView()); }// w w w . j av a2s .c om // transfer the file to a temporary location String originalName = file.getOriginalFilename(); log.debug("Got file: {}", originalName); File tmpFile = new File(resourceDir + "/images/tmp/" + originalName); tmpFile.getParentFile().mkdirs(); file.transferTo(tmpFile); // move the file to the final destination File newFile = new File(resourceDir + "/images/" + url); newFile.getParentFile().mkdirs(); FileUtils.moveFile(tmpFile, newFile); // SUCCESS! response.setStatus(200); return new ModelAndView(new EmptyView()); }
From source file:br.com.alura.casadocodigo.infra.FileSaver.java
public String write(String baseFolder, MultipartFile file) { try {/*from ww w . ja v a 2s.c o m*/ System.out.println("baseFolder " + baseFolder); System.out.println("file " + file); String realPath = request.getServletContext().getRealPath("/") + baseFolder; //String realPath = "H:\\Alura\\casadocodigo\\src\\main\\webapp\\arquivos-sumario"; System.out.println("realPath " + realPath); String path = realPath + "\\" + file.getOriginalFilename(); // String filePath = request.getServletContext().getRealPath("/"); System.out.println("path " + path); file.transferTo(new File(path)); System.out.println("retorno " + baseFolder + "\\" + file.getOriginalFilename()); return baseFolder + "/" + file.getOriginalFilename(); } catch (IOException | IllegalStateException ex) { throw new RuntimeException(ex); } }
From source file:org.spirit.spring.handler.BotListAdminHandler.java
public BotListDocFileMetadata uploadCurFile(HttpServletRequest request, Object form, MultipartFile entity) throws IllegalStateException, IOException { String uploadDir = this.controller.getFileUploadUtil().getUploadDir(); String filename = entity.getOriginalFilename(); String uid = BotListUniqueId.getUniqueId(); String newFilename = "doc" + uid + ".txt"; File fileUpload = new File(uploadDir + "/" + newFilename); entity.transferTo(fileUpload); // Create the file metadata bean BotListDocFileMetadata metadata = new BotListDocFileMetadata(); metadata.setDocFilesize(new Long(entity.getSize())); metadata.setDocFilename(newFilename); metadata.setDocOriginalname(filename); return metadata; }
From source file:com.dbi.jmmerge.MapController.java
private Map<String, File> extractFilesFromZipUpload(MultipartFile file) throws IOException { Map<String, File> ret = new HashMap<>(); String baseDirName = null;//from w w w .j a v a 2s . c om //First catalog it, to see what we've got. File temp = File.createTempFile("map", null); temp.deleteOnExit(); file.transferTo(temp); ZipInputStream zipin = new ZipInputStream(new FileInputStream(temp)); ZipEntry entry = zipin.getNextEntry(); byte[] buf = new byte[1024]; do { FileOutputStream out = null; String filename = entry.getName(); if (isJunkEntry(entry.getName()) || entry.isDirectory()) { continue; } try { ret.put(filename, File.createTempFile(filename, null)); LOG.debug("Incoming timestamp on zip - " + filename + " - " + entry.getTime()); ret.get(filename).deleteOnExit(); out = new FileOutputStream(ret.get(filename)); IOUtils.copy(zipin, out); ret.get(filename).setLastModified(entry.getTime()); } finally { // we must always close the output file if (out != null) out.close(); } } while ((entry = zipin.getNextEntry()) != null); baseDirName = tryToGuessBaseDir(ret.keySet()); if (baseDirName != null) { for (String key : new HashSet<String>(ret.keySet())) { ret.put(key.replace(baseDirName + "/", ""), ret.remove(key)); } } return ret; }
From source file:net.oletalk.hellospringboot.controller.HelloController.java
@PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes attributes) { // multipart file upload is slightly different String originalName = file.getOriginalFilename(); // TODO any way of getting files uploaded without transferring to a temp file? // It seems to want to know the complete path but MultipartFile doesn't give us that. String returnMsg;/*from w ww .j av a 2 s . c o m*/ try { LOG.info("Creating temp file for upload"); File tmpFile = File.createTempFile("s3upload", null); tmpFile.deleteOnExit(); file.transferTo(tmpFile); returnMsg = s3service.uploadDocument("test/" + originalName, tmpFile); attributes.addFlashAttribute("message", returnMsg); } catch (IOException ioe) { LOG.error("Error creating temp file for upload:" + ioe.toString()); attributes.addFlashAttribute("message", "Problem preparing upload to S3"); } return "redirect:/hello/doc/"; }
From source file:org.jahia.modules.webflow.showcase.JobApplication.java
private UploadedFile copy(MultipartFile multipartFile) throws IOException { UploadedFile uploaded = null;/*from w w w . j a va2 s .co m*/ if (multipartFile != null && !multipartFile.isEmpty()) { String originalFilename = multipartFile.getOriginalFilename(); File tmp = File.createTempFile(FilenameUtils.getBaseName(originalFilename), "." + FilenameUtils.getExtension(originalFilename)); multipartFile.transferTo(tmp); uploaded = new UploadedFile(originalFilename, multipartFile.getContentType(), tmp); } return uploaded; }
From source file:it.geosolutions.operations.FileBrowserOperationController.java
@Override public String getJsp(ModelMap model, HttpServletRequest request, List<MultipartFile> files) { System.out.println("getJSP di FileBrowser"); String baseDir = getDefaultBaseDir(); FileBrowser fb = new FileBrowser(); Object gotParam = model.get("gotParam"); @SuppressWarnings("unchecked") Map<String, String[]> parameters = request.getParameterMap(); for (String key : parameters.keySet()) { System.out.println(key); // debug String[] vals = parameters.get(key); for (String val : vals) // debug System.out.println(" -> " + val); // debug if (key.equalsIgnoreCase("d")) { String dirString = parameters.get(key)[0].trim(); // prevent directory traversing dirString = dirString.replace("..", ""); // clean path dirString = dirString.replace("/./", "/"); dirString = dirString.replaceAll("/{2,}", "/"); if (dirString.startsWith("/")) { dirString = dirString.substring(1); }//from w ww .ja va 2 s. c o m //remove last slash if (dirString.lastIndexOf("/") >= 0 && dirString.lastIndexOf("/") == (dirString.length() - 1)) { System.out.println("stripping last slash"); // debug dirString = dirString.substring(0, dirString.length() - 1); } //second check if (dirString.lastIndexOf("/") >= 0) { model.addAttribute("directoryBack", dirString.substring(0, dirString.lastIndexOf("/"))); } else { model.addAttribute("directoryBack", ""); } dirString = dirString.concat("/"); baseDir = baseDir + dirString; model.addAttribute("directory", dirString); } } if (gotParam != null) { System.out.println(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); System.out.println("Deletted " + deleteFileString + ": " + res); // debug } model.addAttribute("operationName", this.operationName); model.addAttribute("operationRESTPath", this.getRESTPath()); fb.setBaseDir(baseDir); fb.setRegex(null); fb.setScanDiretories(canNavigate); if (null != files && files.size() > 0) { List<String> fileNames = new ArrayList<String>(); for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); if (!"".equalsIgnoreCase(fileName)) { try { multipartFile.transferTo(new File(baseDir + fileName)); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } fileNames.add(fileName); } System.out.println(fileName); } } model.addAttribute("fileBrowser", fb); model.addAttribute("operations", getAvailableOperations()); model.addAttribute("canDelete", this.canDelete); model.addAttribute("canUpload", this.canUpload); model.addAttribute("containerId", uniqueKey.toString().substring(0, 8)); model.addAttribute("formId", uniqueKey.toString().substring(27, 36)); return operationJSP; }
From source file:org.openmrs.module.owa.web.controller.OwaRestController.java
@RequestMapping(value = "/rest/owa/addapp", method = RequestMethod.POST) @ResponseBody//from w ww . j a v a 2 s . c o m public List<App> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { List<App> appList = new ArrayList<>(); if (Context.hasPrivilege("Manage OWA")) { String message; HttpSession session = request.getSession(); if (!file.isEmpty()) { String fileName = file.getOriginalFilename(); File uploadedFile = new File(file.getOriginalFilename()); file.transferTo(uploadedFile); try (ZipFile zip = new ZipFile(uploadedFile)) { if (zip.size() == 0) { message = messageSourceService.getMessage("owa.blank_zip"); log.warn("Zip file is empty"); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message); response.sendError(500, message); } else { ZipEntry entry = zip.getEntry("manifest.webapp"); if (entry == null) { message = messageSourceService.getMessage("owa.manifest_not_found"); log.warn("Manifest file could not be found in app"); uploadedFile.delete(); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message); response.sendError(500, message); } else { String contextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath(); appManager.installApp(uploadedFile, fileName, contextPath); message = messageSourceService.getMessage("owa.app_installed"); session.setAttribute(WebConstants.OPENMRS_MSG_ATTR, message); } } } catch (Exception e) { message = messageSourceService.getMessage("owa.not_a_zip"); log.warn("App is not a zip archive"); uploadedFile.delete(); session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, message); response.sendError(500, message); } } appManager.reloadApps(); appList = appManager.getApps(); } return appList; }
From source file:it.geosolutions.operations.FileBrowserOperationController.java
/** * Shows the list of files inside the selected folder after a file upload * @param model// w w w . j av a 2s . com * @return */ //@RequestMapping(value = "/files", method = RequestMethod.POST) public String saveFileAndList(@ModelAttribute("uploadFile") FileUpload uploadFile, ModelMap model) { List<MultipartFile> files = uploadFile.getFiles(); List<String> fileNames = new ArrayList<String>(); if (null != files && files.size() > 0) { for (MultipartFile multipartFile : files) { String fileName = multipartFile.getOriginalFilename(); if (!"".equalsIgnoreCase(fileName)) { //Handle file content - multipartFile.getInputStream() try { multipartFile.transferTo(new File(getDefaultBaseDir() + fileName)); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } fileNames.add(fileName); } System.out.println(fileName); } } model.addAttribute("uploadedFiles", fileNames); FileBrowser fb = new FileBrowser(); fb.setBaseDir(getDefaultBaseDir()); fb.setRegex(null); fb.setScanDiretories(canNavigate); model.addAttribute("fileBrowser", fb); model.addAttribute("operations", getAvailableOperations()); model.addAttribute("context", operationJSP); ControllerUtils.setCommonModel(model); return "template"; }