List of usage examples for org.springframework.web.multipart MultipartFile getBytes
byte[] getBytes() throws IOException;
From source file:org.wise.portal.presentation.web.controllers.admin.ImportProjectController.java
@RequestMapping(value = "/admin/project/import", method = RequestMethod.POST) protected String onSubmit(@ModelAttribute("projectZipFile") ProjectUpload projectUpload, ModelMap modelMap) throws Exception { // TODO: check zip contents for maliciousness. For now, it's only accessible to admin. // uploaded file must be a zip file and have a .zip extension MultipartFile file = projectUpload.getFile(); String zipFilename = file.getOriginalFilename(); byte[] fileBytes = file.getBytes(); String msg = "Import project complete!"; Project project = importProject(zipFilename, fileBytes); if (project == null) { System.err.println("Error occured during project import."); msg = "Error occured during project import. Check the log for more information."; }/*from w w w . j av a 2 s . com*/ modelMap.put("msg", msg); modelMap.put("newProject", project); return "admin/project/import"; }
From source file:org.wise.vle.web.AssetManager.java
/** * Uploads the specified file to the given path. * @param file the file that is to be uploaded * @param path the path to the project folder or the student uploads base directory * @param dirName the folder name to upload to which will be assets or the directory * for a workgroup for a run//from ww w .ja v a 2 s . co m * @param pathToCheckSize the path to check the disk space usage for. if we are uploading * to a project we will check the whole project folder size. if we are uploading to a * student folder we will check that student folder * @param maxTotalAssetsSize the the max disk space usage allowable * @return true iff saving the asset was successful */ @SuppressWarnings("unchecked") public static Boolean uploadAssetWISE5(MultipartFile file, String path, String dirName, String pathToCheckSize, Long maxTotalAssetsSize) { try { File projectDir = new File(path); File assetsDir = new File(projectDir, dirName); if (!assetsDir.exists()) { assetsDir.mkdirs(); } if (SecurityUtils.isAllowedAccess(path, assetsDir)) { //String successMessage = ""; String filename = file.getOriginalFilename(); File asset = new File(assetsDir, filename); byte[] content = file.getBytes(); if (Long.parseLong(getFolderSize(pathToCheckSize)) + content.length > maxTotalAssetsSize) { //successMessage += "Uploading " + filename + " of size " + appropriateSize(content.length) + " would exceed your maximum storage capacity of " + appropriateSize(maxTotalAssetsSize) + ". Operation aborted."; return false; } else { if (!asset.exists()) { asset.createNewFile(); } FileOutputStream fos = new FileOutputStream(asset); fos.write(content); fos.flush(); fos.close(); //successMessage += asset.getName() + " was successfully uploaded! "; } if ("application/zip".equals(file.getContentType()) || "application/x-zip".equals(file.getContentType()) || "application/x-zip-compressed".equals(file.getContentType())) { // if user uploaded a zip file, unzip it ZipFile zipFile = new ZipFile(asset); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(assetsDir, entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { File parent = entryDestination.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } //successMessage += "WISE also extracted files from the zip file! "; } else { } return true; } else { return false; } } catch (Exception e) { e.printStackTrace(); return false; } }
From source file:org.wise.vle.web.AssetManager.java
/** * Uploads the specified file to the given path. * @param fileMap the files that are to be uploaded * @param path the path to the project folder or the student uploads base directory * @param dirName the folder name to upload to which will be assets or the directory * for a workgroup for a run//from w w w . j a va2 s . co m * @param pathToCheckSize the path to check the disk space usage for. if we are uploading * to a project we will check the whole project folder size. if we are uploading to a * student folder we will check that student folder * @param maxTotalAssetsSizethe the max disk space usage allowable * @return the message of the status of the upload */ @SuppressWarnings("unchecked") public static String uploadAsset(Map<String, MultipartFile> fileMap, String path, String dirName, String pathToCheckSize, Long maxTotalAssetsSize) { try { /* file upload is coming from the portal so we need to read the bytes * that the portal set in the attribute */ File projectDir = new File(path); File assetsDir = new File(projectDir, dirName); if (!assetsDir.exists()) { assetsDir.mkdirs(); } if (SecurityUtils.isAllowedAccess(path, assetsDir)) { String successMessage = ""; if (fileMap != null && fileMap.size() > 0) { Set<String> keySet = fileMap.keySet(); Iterator<String> iter = keySet.iterator(); while (iter.hasNext()) { String key = iter.next(); MultipartFile file = fileMap.get(key); String filename = file.getOriginalFilename(); File asset = new File(assetsDir, filename); byte[] content = file.getBytes(); if (Long.parseLong(getFolderSize(pathToCheckSize)) + content.length > maxTotalAssetsSize) { successMessage += "Uploading " + filename + " of size " + appropriateSize(content.length) + " would exceed your maximum storage capacity of " + appropriateSize(maxTotalAssetsSize) + ". Operation aborted."; } else { if (!asset.exists()) { asset.createNewFile(); } FileOutputStream fos = new FileOutputStream(asset); fos.write(content); fos.flush(); fos.close(); successMessage += asset.getName() + " was successfully uploaded! "; } if ("application/zip".equals(file.getContentType()) || "application/x-zip".equals(file.getContentType()) || "application/x-zip-compressed".equals(file.getContentType())) { // check if unzipped folder already exists. If so, delete it first. String unzippedFolderName = filename.substring(0, filename.lastIndexOf(".zip")); File unzippedFolder = new File(assetsDir, unzippedFolderName); if (unzippedFolder.exists()) { FileUtils.deleteDirectory(unzippedFolder); } // if user uploaded a zip file, unzip it ZipFile zipFile = new ZipFile(asset); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(assetsDir, entry.getName()); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { File parent = entryDestination.getParentFile(); if (!parent.exists() && !parent.mkdirs()) { throw new IllegalStateException("Couldn't create dir: " + parent); } InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } successMessage += "WISE also extracted files from the zip file! "; } else { } } } return successMessage; } else { return "Access to path is denied."; } } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } }
From source file:pl.edu.icm.cermine.web.controller.CermineController.java
@RequestMapping(value = "/upload.do", method = RequestMethod.POST) public String uploadFileStream(@RequestParam("files") MultipartFile file, HttpServletRequest request, Model model) {//from w ww . java2 s . c om logger.info("Got an upload request."); try { byte[] content = file.getBytes(); if (content.length == 0) { model.addAttribute("warning", "An empty or no file sent."); return "home"; } String filename = file.getOriginalFilename(); logger.debug("Original filename is: " + filename); filename = taskManager.getProperFilename(filename); logger.debug("Created filename: " + filename); long taskId = extractorService.initExtractionTask(content, filename); logger.debug("Task manager is: " + taskManager); return "redirect:/task.html?task=" + taskId; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:sg.ncl.MainController.java
@RequestMapping(path = "/show_pub_keys", method = RequestMethod.POST) public String addPublicKey(@RequestParam("keyFile") MultipartFile keyFile, @RequestParam("keyPass") String keyPass, RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException { if (keyFile.isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Please select a keyfile to upload"); redirectAttributes.addFlashAttribute("hasKeyFileError", true); } else if (keyPass.isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Please enter your password"); redirectAttributes.addFlashAttribute("hasKeyPassError", true); } else {// w ww. j av a 2 s. c o m try { JSONObject keyInfo = new JSONObject(); keyInfo.put("publicKey", new String(keyFile.getBytes())); keyInfo.put(PSWD, keyPass); HttpEntity<String> request = createHttpEntityWithBody(keyInfo.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange( properties.getPublicKeys(session.getAttribute("id").toString()), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case VERIFICATION_PASSWORD_NOT_MATCH_EXCEPTION: log.error(error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, "Invalid password"); redirectAttributes.addFlashAttribute("hasKeyPassError", true); break; case INVALID_PUBLIC_KEY_FILE_EXCEPTION: log.error(error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, "Invalid key file"); break; case INVALID_PUBLIC_KEY_FORMAT_EXCEPTION: log.error(error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, "Invalid key format"); break; case FORBIDDEN_EXCEPTION: log.error(error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, "Adding of public key is forbidden"); break; default: log.error("Unknown error when adding public key"); redirectAttributes.addFlashAttribute(MESSAGE, "Unknown error when adding public key"); } } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } return "redirect:/show_pub_keys"; }
From source file:ua.aits.Carpath.controller.ArchiveController.java
@RequestMapping(value = { "/system/archive/do/uploadfile", "/system/archive/do/uploadfile/", "/Carpath/system/archive/do/uploadfile", "/Carpath/system/archive/do/uploadfile/" }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandler(@RequestParam("file") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { String name = file.getOriginalFilename(); if (!file.isEmpty()) { try {/*w w w .j av a2 s . c o m*/ byte[] bytes = file.getBytes(); File dir = new File(Constants.HOME + path); if (!dir.exists()) dir.mkdirs(); File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } return ""; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:ua.aits.Carpath.controller.ArchiveController.java
@RequestMapping(value = { "/system/archive/do/uploadimage", "/system/archive/do/uploadimage/", "/Carpath/system/archive/do/uploadimage", "/Carpath/system/archive/do/uploadimage/" }, method = RequestMethod.POST) public @ResponseBody String uploadImageHandler(@RequestParam("file") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { String name = file.getOriginalFilename(); if (!file.isEmpty()) { try {/*from www . jav a 2 s. co m*/ byte[] bytes = file.getBytes(); File dir = new File(Constants.HOME + path); if (!dir.exists()) dir.mkdirs(); File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } return ""; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:ua.aits.Carpath.controller.FileUploadController.java
/** * Upload single file using Spring Controller * @param file//from w w w .j av a 2 s . c o m * @param path * @param request * @return */ @RequestMapping(value = { "/uploadFile", "/Carpath/uploadFile", }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandler(@RequestParam("upload") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { String name = file.getOriginalFilename(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file File dir = new File(Constants.HOME + path); if (!dir.exists()) dir.mkdirs(); // Create the file on server File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } String link_path = serverFile.getAbsolutePath().replace(Constants.HOME, ""); return "<a href=\"#\" class=\"returnImage\" data-url='" + Constants.URL + path + name + "'>" + "<img src=\"" + Constants.URL + link_path + "\" realpath='" + link_path + "' alt='" + link_path + file.getName() + "' /><img src='" + Constants.URL + "img/remove.png' class='remove-icon'/></a>"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:ua.aits.Carpath.controller.FileUploadController.java
@RequestMapping(value = { "/uploadIcon", "/Carpath/uploadIcon" }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandlerMarker(@RequestParam("upload") MultipartFile file, HttpServletRequest request) {//w w w . j a v a2s. c om String name = file.getOriginalFilename(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file File dir = new File(Constants.FILE_URL_ICON); File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } return "<a class=\"returnImage\" data-url='" + Constants.URL + "img/markerImages/" + name + "'>" + "<img src='" + Constants.URL + "img/content/" + name + "' alt='" + name + "' /><img src='" + Constants.URL + "img/remove.png' class='remove-icon'/></a>"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }
From source file:ua.aits.Carpath.controller.FileUploadController.java
@RequestMapping(value = { "/system/uploadRoute", "/Carpath/system/uploadRoute" }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandlerRoute(@RequestParam("upload") MultipartFile file, HttpServletRequest request) {// www. j a va 2 s . c om String name = file.getOriginalFilename(); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // Creating the directory to store file File dir = new File(Constants.FILE_URL_ROUTES); File serverFile = new File(dir.getAbsolutePath() + File.separator + name); try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile))) { stream.write(bytes); } return name; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }