List of usage examples for org.springframework.web.multipart MultipartFile getSize
long getSize();
From source file:io.lavagna.web.api.CardDataController.java
@ExpectPermission(Permission.CREATE_FILE) @RequestMapping(value = "/api/card/{cardId}/file", method = RequestMethod.POST) @ResponseBody// w w w . j a v a 2 s . c o m public List<String> uploadFiles(@PathVariable("cardId") int cardId, @RequestParam("files") List<MultipartFile> files, User user, HttpServletResponse resp) throws IOException { LOG.debug("Files uploaded: {}", files.size()); if (!ensureFileSize(files)) { resp.setStatus(422); return Collections.emptyList(); } List<String> digests = new ArrayList<>(); for (MultipartFile file : files) { Path p = Files.createTempFile("lavagna", "upload"); try (InputStream fileIs = file.getInputStream()) { Files.copy(fileIs, p, StandardCopyOption.REPLACE_EXISTING); String digest = DigestUtils.sha256Hex(Files.newInputStream(p)); String contentType = file.getContentType() != null ? file.getContentType() : "application/octet-stream"; boolean result = cardDataService.createFile(file.getOriginalFilename(), digest, file.getSize(), cardId, Files.newInputStream(p), contentType, user, new Date()).getLeft(); if (result) { LOG.debug("file uploaded! size: {}, original name: {}, content-type: {}", file.getSize(), file.getOriginalFilename(), file.getContentType()); digests.add(digest); } } finally { Files.delete(p); LOG.debug("deleted temp file {}", p); } } eventEmitter.emitUploadFile(cardRepository.findBy(cardId).getColumnId(), cardId); return digests; }
From source file:com.qcadoo.mes.basic.controllers.WorkstationMultiUploadController.java
@ResponseBody @RequestMapping(value = "/multiUploadFiles", method = RequestMethod.POST) public void upload(MultipartHttpServletRequest request, HttpServletResponse response) { Long workstationId = Long.parseLong(request.getParameter("techId")); Entity workstation = dataDefinitionService .get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_WORKSTATION).get(workstationId); DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_WORKSTATION_ATTACHMENT); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null; while (itr.hasNext()) { mpf = request.getFile(itr.next()); String path = ""; try {//from w ww . j a va 2 s . com path = fileService.upload(mpf); } catch (IOException e) { logger.error("Unable to upload attachment.", e); } if (exts.contains(Files.getFileExtension(path).toUpperCase())) { Entity atchment = attachmentDD.create(); atchment.setField(WorkstationAttachmentFields.ATTACHMENT, path); atchment.setField(WorkstationAttachmentFields.NAME, mpf.getOriginalFilename()); atchment.setField(WorkstationAttachmentFields.WORKSTATION, workstation); atchment.setField(WorkstationAttachmentFields.EXT, Files.getFileExtension(path)); BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext()); BigDecimal divider = new BigDecimal(1024, numberService.getMathContext()); BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP); atchment.setField(WorkstationAttachmentFields.SIZE, size); attachmentDD.save(atchment); } } }
From source file:com.qcadoo.mes.basic.controllers.SubassemblyMultiUploadController.java
@ResponseBody @RequestMapping(value = "/multiUploadFilesForSubassembly", method = RequestMethod.POST) public void upload(MultipartHttpServletRequest request, HttpServletResponse response) { Long subassemblyId = Long.parseLong(request.getParameter("techId")); Entity subassembly = dataDefinitionService .get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_SUBASSEMBLY).get(subassemblyId); DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER, BasicConstants.MODEL_SUBASSEMBLY_ATTACHMENT); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null; while (itr.hasNext()) { mpf = request.getFile(itr.next()); String path = ""; try {// ww w . java 2 s . c o m path = fileService.upload(mpf); } catch (IOException e) { logger.error("Unable to upload attachment.", e); } if (exts.contains(Files.getFileExtension(path).toUpperCase())) { Entity atchment = attachmentDD.create(); atchment.setField(SubassemblyAttachmentFields.ATTACHMENT, path); atchment.setField(SubassemblyAttachmentFields.NAME, mpf.getOriginalFilename()); atchment.setField(SubassemblyAttachmentFields.SUBASSEMBLY, subassembly); atchment.setField(SubassemblyAttachmentFields.EXT, Files.getFileExtension(path)); BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext()); BigDecimal divider = new BigDecimal(1024, numberService.getMathContext()); BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP); atchment.setField(SubassemblyAttachmentFields.SIZE, size); attachmentDD.save(atchment); } } }
From source file:net.duckling.ddl.web.sync.FileContentController.java
@RequestMapping(value = "/upload_session/append", method = RequestMethod.POST) public void appendUploadSession(HttpServletRequest request, HttpServletResponse response, @RequestParam("session_id") String sessionId, @RequestParam("chunk_index") Integer chunkIndex, @RequestParam("chunk_data") MultipartFile chunkData) { ChunkUploadSession chunkUploadSession = chunkUploadSessionService.get(sessionId); if (chunkUploadSession == null) { JsonResponse.chunkUploadSessionNotFound(response, sessionId); return;/*w w w . j av a 2 s. c o m*/ } ChunkResponse chunkResponse = null; try { chunkResponse = fileStorage.executeChunkUpload(chunkUploadSession.getClbId().intValue(), chunkIndex, chunkData.getBytes(), (int) chunkData.getSize()); } catch (IOException e) { JsonResponse.error(response); LOG.error(String.format("Fail to upload chunk %d of clbid %d.", chunkIndex, chunkUploadSession.getClbId()), e); return; } if (chunkResponse.isSccuessStatus()) { JsonResponse.ackChunk(response, sessionId, "ack", chunkResponse.getEmptyChunkSet()); } else if (chunkResponse.isDuplicateChunk()) { JsonResponse.ackChunk(response, sessionId, "duplicated", chunkResponse.getEmptyChunkSet()); } else if (chunkResponse.getStatusCode() == ChunkResponse.CHUNK_INDEX_INVALID) { JsonResponse.ackChunk(response, sessionId, "invalid_index", null); } else if (chunkResponse.getStatusCode() == ChunkResponse.EXCEED_MAX_CHUNK_SIZE) { JsonResponse.error(response); } else { JsonResponse.error(response); } }
From source file:com.qcadoo.mes.cmmsMachineParts.controller.PlannedEventMultiUploadController.java
@ResponseBody @RequestMapping(value = "/multiUploadFilesForPlannedEvent", method = RequestMethod.POST) public void upload(MultipartHttpServletRequest request, HttpServletResponse response) { Long eventId = Long.parseLong(request.getParameter("eventId")); Entity event = dataDefinitionService .get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_PLANNED_EVENT) .get(eventId);// w w w .ja v a 2 s . c o m DataDefinition attachmentDD = dataDefinitionService.get(CmmsMachinePartsConstants.PLUGIN_IDENTIFIER, CmmsMachinePartsConstants.MODEL_PLANNED_EVENT_ATTACHMENT); Iterator<String> itr = request.getFileNames(); MultipartFile mpf = null; while (itr.hasNext()) { mpf = request.getFile(itr.next()); String path = ""; try { path = fileService.upload(mpf); } catch (IOException e) { logger.error("Unable to upload attachment.", e); } if (exts.contains(Files.getFileExtension(path).toUpperCase())) { Entity atchment = attachmentDD.create(); atchment.setField(PlannedEventAttachmentFields.ATTACHMENT, path); atchment.setField(PlannedEventAttachmentFields.NAME, mpf.getOriginalFilename()); atchment.setField(PlannedEventAttachmentFields.PLANNED_EVENT, event); atchment.setField(PlannedEventAttachmentFields.EXT, Files.getFileExtension(path)); BigDecimal fileSize = new BigDecimal(mpf.getSize(), numberService.getMathContext()); BigDecimal divider = new BigDecimal(1024, numberService.getMathContext()); BigDecimal size = fileSize.divide(divider, L_SCALE, BigDecimal.ROUND_HALF_UP); atchment.setField(PlannedEventAttachmentFields.SIZE, size); atchment = attachmentDD.save(atchment); atchment.isValid(); } } }
From source file:com.mbv.web.rest.controller.VpGdnController.java
/** * @??excel/* w ww . j a v a 2s .c o m*/ * @2015916 * @param * @version */ @RequestMapping(value = "/importGdn", method = RequestMethod.POST) @ResponseBody public void importVpGdnAddBill( @RequestParam(value = "add_vpGdn_importedFile", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { JSONObject json = new JSONObject(); try { // ? if (file.isEmpty()) { throw new MbvException("??"); } // ?? if (file.getSize() > 20971520) { throw new Exception("?20M?"); } json = importFile(file); } catch (MbvException me) { me.printStackTrace(); json.put("success", false); json.put("msg", me.getMessage()); } catch (RuntimeException re) { re.printStackTrace(); json.put("success", false); json.put("msg", re.getMessage()); } catch (Exception e) { e.printStackTrace(); json.put("success", false); json.put("msg", e.getMessage()); } // ??? outPrintJson(response, json.toString()); }
From source file:com.mbv.web.rest.controller.VpGdnController.java
/** * @??excel//from w ww . j av a2 s .co m * @2015916 * @param * @version */ @RequestMapping(value = "/importUpdateGdn", method = RequestMethod.POST) @ResponseBody public void importVpGdnUpdateBill( @RequestParam(value = "update_vpGdn_importedFile", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException { JSONObject json = new JSONObject(); try { // ? if (file.isEmpty()) { throw new MbvException("??"); } // ?? if (file.getSize() > 20971520) { throw new Exception("?20M?"); } json = importFile(file); } catch (MbvException me) { me.printStackTrace(); json.put("success", false); json.put("msg", me.getMessage()); } catch (RuntimeException re) { re.printStackTrace(); json.put("success", false); json.put("msg", re.getMessage()); } catch (Exception e) { e.printStackTrace(); json.put("success", false); json.put("msg", e.getMessage()); } // ??? outPrintJson(response, json.toString()); }
From source file:cz.zcu.kiv.eegdatabase.webservices.rest.scenario.ScenarioServiceImpl.java
/** * {@inheritDoc}//ww w . j a v a 2 s.co m */ @Override @Transactional public int create(ScenarioData scenarioData, MultipartFile file) throws IOException, SAXException, ParserConfigurationException { Scenario scenario = new Scenario(); scenario.setDescription(scenarioData.getDescription()); scenario.setTitle(scenarioData.getScenarioName()); scenario.setScenarioName(file.getOriginalFilename().replace(" ", "_")); scenario.setMimetype(scenarioData.getMimeType().toLowerCase().trim()); //DB column size restriction if (scenario.getMimetype().length() > 30) { scenario.setMimetype("application/octet-stream"); } ResearchGroup group = researchGroupDao.read(scenarioData.getResearchGroupId()); scenario.setResearchGroup(group); Person owner = personDao.getLoggedPerson(); scenario.setPerson(owner); scenario.setScenarioLength((int) file.getSize()); scenario.setPrivateScenario(scenarioData.isPrivate()); return scenarioDao.create(scenario); }
From source file:edu.unc.lib.dl.admin.controller.IngestController.java
@RequestMapping(value = "ingest/{pid}", method = RequestMethod.POST) public @ResponseBody Map<String, ? extends Object> ingestPackageController(@PathVariable("pid") String pid, @RequestParam("type") String type, @RequestParam(value = "name", required = false) String name, @RequestParam("file") MultipartFile ingestFile, HttpServletRequest request, HttpServletResponse response) {/*from w w w .j a v a 2 s . co m*/ String destinationUrl = swordUrl + "collection/" + pid; HttpClient client = HttpClientUtil.getAuthenticatedClient(destinationUrl, swordUsername, swordPassword); client.getParams().setAuthenticationPreemptive(true); PostMethod method = new PostMethod(destinationUrl); // Set SWORD related headers for performing ingest method.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString()); method.addRequestHeader("Packaging", type); method.addRequestHeader("On-Behalf-Of", GroupsThreadStore.getUsername()); method.addRequestHeader("Content-Type", ingestFile.getContentType()); method.addRequestHeader("Content-Length", Long.toString(ingestFile.getSize())); method.addRequestHeader("mail", request.getHeader("mail")); method.addRequestHeader("Content-Disposition", "attachment; filename=" + ingestFile.getOriginalFilename()); if (name != null && name.trim().length() > 0) method.addRequestHeader("Slug", name); // Setup the json response Map<String, Object> result = new HashMap<String, Object>(); result.put("action", "ingest"); result.put("destination", pid); try { method.setRequestEntity( new InputStreamRequestEntity(ingestFile.getInputStream(), ingestFile.getSize())); client.executeMethod(method); response.setStatus(method.getStatusCode()); // Object successfully "create", or at least queued if (method.getStatusCode() == 201) { Header location = method.getResponseHeader("Location"); String newPid = location.getValue(); newPid = newPid.substring(newPid.lastIndexOf('/')); result.put("pid", newPid); } else if (method.getStatusCode() == 401) { // Unauthorized result.put("error", "Not authorized to ingest to container " + pid); } else if (method.getStatusCode() == 400 || method.getStatusCode() >= 500) { // Server error, report it to the client result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); // Inspect the SWORD response, extracting the stacktrace InputStream entryPart = method.getResponseBodyAsStream(); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<Entry> entryDoc = parser.parse(entryPart); Object rootEntry = entryDoc.getRoot(); String stackTrace; if (rootEntry instanceof FOMExtensibleElement) { stackTrace = ((org.apache.abdera.parser.stax.FOMExtensibleElement) entryDoc.getRoot()) .getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } else { stackTrace = ((Entry) rootEntry).getExtension(SWORD_VERBOSE_DESCRIPTION).getText(); result.put("errorStack", stackTrace); } log.warn("Failed to upload ingest package file " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), stackTrace); } return result; } catch (Exception e) { log.warn("Encountered an unexpected error while ingesting package " + ingestFile.getName() + " from user " + GroupsThreadStore.getUsername(), e); result.put("error", "A server error occurred while attempting to ingest \"" + ingestFile.getName() + "\" to " + pid); return result; } finally { method.releaseConnection(); try { ingestFile.getInputStream().close(); } catch (IOException e) { log.warn("Failed to close ingest package file", e); } } }
From source file:controllers.admin.PostController.java
@PostMapping("/save") public String processPost(@RequestPart("postImage") MultipartFile postImage, @ModelAttribute(ATTRIBUTE_NAME) @Valid Post post, BindingResult bindingResult, @CurrentUserAttached User activeUser, RedirectAttributes model) throws IOException, SQLException { String url = "redirect:/admin/posts/all"; if (post.getImage() == null && postImage != null && postImage.isEmpty()) { bindingResult.rejectValue("image", "post.image.notnull"); }/* www.j a v a 2 s. c o m*/ if (bindingResult.hasErrors()) { model.addFlashAttribute(BINDING_RESULT_NAME, bindingResult); return url; } if (postImage != null && !postImage.isEmpty()) { logger.info("Aadiendo informacin de la imagen"); FileImage image = new FileImage(); image.setName(postImage.getName()); image.setContentType(postImage.getContentType()); image.setSize(postImage.getSize()); image.setContent(postImage.getBytes()); post.setImage(image); } post.setAuthor(activeUser); if (post.getId() == null) { postService.create(post); } else { postService.edit(post); } List<String> successMessages = new ArrayList(); successMessages.add(messageSource.getMessage("message.post.save.success", new Object[] { post.getId() }, Locale.getDefault())); model.addFlashAttribute("successFlashMessages", successMessages); return url; }