List of usage examples for javax.servlet.http Part getInputStream
public InputStream getInputStream() throws IOException;
From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java
private Part createPart(String name, InputStream inputStream, String contentDisposition) throws IOException { Part part = mock(Part.class); when(part.getName()).thenReturn(name); when(part.getInputStream()).thenReturn(inputStream); when(part.getHeader("Content-Disposition")).thenReturn(contentDisposition); when(part.getContentType()).thenReturn(MediaType.APPLICATION_OCTET_STREAM); return part;/*ww w . j a v a 2 s . c om*/ }
From source file:com.kirayim.homesec.service.impl.ImageManagerImpl.java
@Override public Image handleFileUpload(long cameraId, HttpServletRequest request) { String extension = null;// w w w .jav a2 s. c o m Date uploadTime = new Date(); String encoding = request.getCharacterEncoding(); if (encoding == null) { try { request.setCharacterEncoding(encoding = "UTF-8"); } catch (UnsupportedEncodingException ex) { logger.warn("Bad encoding", ex); } } User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Camera camera = cameraManager.get(cameraId); if (camera == null) { throw new NotAllowedException("Imvalid camera ID"); } if (!camera.getOwner().equals(user)) { throw new NotAllowedException("Camera doesn't belong to current user"); } /* ------------------------------------------------- * Calculate output file name * ------------------------------------------------- */ String name = String.format("homesec_image_%1$08d_%2$TY%2$Tm%2$Td_%2$TH%2$TM%2$TS%2$TL", camera.getCameraId(), uploadTime); /* ------------------------------------------------- * Get uploaded file and write to destination * ------------------------------------------------- */ try { if (request.getParts().size() > 1) { throw new NotAllowedException("Only one image upload per transaction"); } for (Part part : request.getParts()) { if (!uploadDir.exists()) { uploadDir.mkdirs(); } String contentType = part.getContentType(); if (contentType != null) { try { MimeTypes allTypes = MimeTypes.getDefaultMimeTypes(); MimeType mimeType = allTypes.forName(contentType); extension = mimeType.getExtension(); name += extension; } catch (MimeTypeException mimeTypeException) { logger.warn("Mime? ", mimeTypeException); } } File outputFile = new File(uploadDir, name); OutputStream out = new FileOutputStream(outputFile); InputStream in = part.getInputStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } catch (IOException | ServletException e) { throw new BadRequestException(e); } /* ------------------------------------------------- * If extension is unknown, re-read file to try * and get extension * ------------------------------------------------- */ if (extension == null) { // TODO: } /* ------------------------------------------------- * Save image record in DB * ------------------------------------------------- */ Image image = new Image(camera, name, uploadTime); dao.save(image); return image; }
From source file:fr.lirmm.yamplusplus.yampponline.YamFileHandler.java
/** * Upload a file from HTTP request. It downloads the file if it is an URL or * get it from the POST request. It stores the contentString in a file in the * tmp directory. In a subdirectory /tmp/yam-gui/ + subDir generated + / + * filename (source.owl or target.owl). Usually the sub directory is randomly * generated before calling uploadFile And return the path to the created * file. OntName can be "source" or "target" * * @param ontName//from w w w .j av a2 s . c o m * @param subDir * @param request * @return file storage path * @throws IOException * @throws java.net.URISyntaxException * @throws javax.servlet.ServletException */ public String uploadFile(String ontName, String subDir, HttpServletRequest request) throws IOException, URISyntaxException, ServletException { // Store given ontology in /tmp/yam-gui/SUBDIR/source.owl String storagePath = this.tmpDir + subDir + "/" + ontName + ".owl"; // Check if an URL have been provided String ontologyUrl = request.getParameter(ontName + "Url"); // Use URL in priority. If not, then get the uploaded file from the form if (ontologyUrl != null && !ontologyUrl.isEmpty()) { //ontologyString = getUrlContent(ontologyUrl); TO REMOVE // Copy file from remote URL SystemUtils.copyFileFromURL(new URI(ontologyUrl), storagePath); } else { // Get file from uploaded file in form Part filePart = null; Logger.getLogger(Matcher.class.getName()).log(Level.INFO, "Justeeee AVANT request.getPart(fileParam) dans readFileFromRequest"); // Retrieve file from input where name is sourceFile or targetFile filePart = request.getPart(ontName + "File"); if (filePart != null) { //String uploadedFilename = filePart.getSubmittedFileName(); //storagePath = this.tmpDir + subDir + "/" + uploadedFilename; InputStream fileStream = filePart.getInputStream(); // Write InputStream to file File storageFile = new File(storagePath); storageFile.getParentFile().mkdirs(); java.nio.file.Files.copy(fileStream, storageFile.toPath(), StandardCopyOption.REPLACE_EXISTING); IOUtils.closeQuietly(fileStream); } } Logger.getLogger(Matcher.class.getName()).log(Level.SEVERE, "End uploadFileee"); // Store ontology in workDir if asked (/srv/yam-gui/save/field/username) return storagePath; }
From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java
@RequestMapping(value = "/channel/import", method = RequestMethod.POST) public ModelAndView importChannelPost(@RequestParameter("file") final Part part, @RequestParameter(value = "useName", required = false) final boolean useName) { try {/*from www .j a v a 2s . c o m*/ final Channel channel = this.service.importChannel(part.getInputStream(), useName); return new ModelAndView("redirect:/channel/" + channel.getId() + "/view"); } catch (final Exception e) { logger.warn("Failed to import", e); return CommonController.createError("Import", "Channel", "Failed to import channel", e, null); } }
From source file:gob.dp.simco.registro.controller.ActaAcuerdoController.java
private String uploadArchive(Part fil) { String nameArchive = getFilename(fil); String extencion = getFileExtension(getFilename(fil)); if (StringUtils.isNoneBlank(nameArchive)) { String formato = RandomStringUtils.random(32, 0, 20, true, true, "qw32rfHIJk9iQ8Ud7h0X".toCharArray()); String ruta = formato + extencion; File file = new File(ConstantesUtil.FILE_SYSTEM + ruta); try (InputStream input = fil.getInputStream()) { Files.copy(input, file.toPath()); } catch (IOException ex) { log.error(ex);//from w w w .ja v a 2s. c o m } return ruta; } return null; }
From source file:com.contact.ContactController.java
@RequestMapping(method = RequestMethod.POST) public String create(@Valid Contact contact, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, RedirectAttributes redirectAttributes, Locale locale, @RequestParam(value = "file", required = false) Part file) { logger.info("Creating contact"); if (bindingResult.hasErrors()) { uiModel.addAttribute("message", new Message("error", messageSource.getMessage("contact_save_fail", new Object[] {}, locale))); uiModel.addAttribute("contact", contact); return "contacts/create"; }// w ww.j av a 2s .co m uiModel.asMap().clear(); redirectAttributes.addFlashAttribute("message", new Message("success", messageSource.getMessage("contact_save_success", new Object[] {}, locale))); logger.info("Contact id: " + contact.getId()); // Process upload file if (file != null) { logger.info("File name: " + file.getName()); logger.info("File size: " + file.getSize()); logger.info("File content type: " + file.getContentType()); byte[] fileContent = null; try { InputStream inputStream = file.getInputStream(); if (inputStream == null) logger.info("File inputstream is null"); fileContent = IOUtils.toByteArray(inputStream); contact.setPhoto(fileContent); } catch (IOException ex) { logger.error("Error saving uploaded file"); } contact.setPhoto(fileContent); } contactService.save(contact); return "redirect:/contacts/"; }
From source file:com.matrimony.controller.ProfileController.java
@RequestMapping(value = "changeAvatar", method = RequestMethod.POST) public String doChangeAvatar(HttpServletRequest request) { User ssUser = (User) request.getSession().getAttribute(SessionKey.USER); if (ssUser == null) return "joinUs"; try {//from w w w.j av a 2s. c om Collection<Part> parts = request.getParts(); for (Part p : parts) { String originName = p.getSubmittedFileName(); if (originName != null) { System.out.println(originName); String[] extensionFile = originName.split("\\."); if (extensionFile.length > 1) { String avatarFolderPath = request.getServletContext() .getRealPath("/resources/profile/avatar"); System.out.println("avatar folder: " + avatarFolderPath); // MAKE OBF NAME AVATAR IMAGE String obfName = RandomStringUtils.randomAlphanumeric(26); StringBuilder filePath = new StringBuilder(avatarFolderPath); filePath.append("/"); filePath.append(obfName); filePath.append("."); filePath.append(extensionFile[1]); UploadImageToServer upload = new UploadImageToServer(); upload.upload(filePath.toString(), p.getInputStream()); System.out.println("Uploaded " + filePath.toString()); // UPDATE AVATAR UserDAO.Update(ssUser); ssUser.setAvatarPhoto(obfName + "." + extensionFile[1]); return "redirect:"; } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "profile"; }
From source file:org.codice.ddf.rest.impl.CatalogServiceImpl.java
@Override public Map.Entry<AttachmentInfo, Metacard> parseParts(Collection<Part> contentParts, String transformerParam) { if (contentParts.size() == 1) { Part part = Iterables.get(contentParts, 0); try (InputStream inputStream = part.getInputStream()) { ContentDisposition contentDisposition = new ContentDisposition( part.getHeader(HEADER_CONTENT_DISPOSITION)); return new ImmutablePair<>( attachmentParser.generateAttachmentInfo(inputStream, part.getContentType(), contentDisposition.getParameter(FILENAME_CONTENT_DISPOSITION_PARAMETER_NAME)), null);/*from w w w .j av a 2s.c o m*/ } catch (IOException e) { LOGGER.debug("IOException reading stream from file attachment in multipart body.", e); } } Metacard metacard = null; AttachmentInfo attachmentInfo = null; Map<String, AttributeImpl> attributeMap = new HashMap<>(); for (Part part : contentParts) { String name = part.getName(); String parsedName = (name.startsWith("parse.")) ? name.substring(6) : name; try (InputStream inputStream = part.getInputStream()) { ContentDisposition contentDisposition = new ContentDisposition( part.getHeader(HEADER_CONTENT_DISPOSITION)); switch (name) { case "parse.resource": attachmentInfo = attachmentParser.generateAttachmentInfo(inputStream, part.getContentType(), contentDisposition.getParameter(FILENAME_CONTENT_DISPOSITION_PARAMETER_NAME)); break; case "parse.metadata": metacard = parseMetacard(transformerParam, metacard, part, inputStream); break; default: parseOverrideAttributes(attributeMap, parsedName, inputStream); break; } } catch (IOException e) { LOGGER.debug("Unable to get input stream for mime attachment. Ignoring override attribute: {}", name, e); } } if (attachmentInfo == null) { throw new IllegalArgumentException("No parse.resource specified in request."); } if (metacard == null) { metacard = new MetacardImpl(); } Set<AttributeDescriptor> missingDescriptors = new HashSet<>(); for (Attribute attribute : attributeMap.values()) { if (metacard.getMetacardType().getAttributeDescriptor(attribute.getName()) == null) { attributeRegistry.lookup(attribute.getName()).ifPresent(missingDescriptors::add); } metacard.setAttribute(attribute); } if (!missingDescriptors.isEmpty()) { MetacardType original = metacard.getMetacardType(); MetacardImpl newMetacard = new MetacardImpl(metacard); newMetacard.setType(new MetacardTypeImpl(original.getName(), original, missingDescriptors)); metacard = newMetacard; } return new ImmutablePair<>(attachmentInfo, metacard); }
From source file:de.dentrassi.pm.storage.web.channel.ChannelController.java
@RequestMapping(value = "/channel/{channelId}/add", method = RequestMethod.POST) public ModelAndView addPost(@PathVariable("channelId") final String channelId, @RequestParameter(required = false, value = "name") String name, final @RequestParameter("file") Part file) { try {/*from w ww . ja va 2s . c o m*/ if (name == null || name.isEmpty()) { name = file.getSubmittedFileName(); } final String finalName = name; this.channelService.access(By.id(channelId), ModifiableChannel.class, channel -> { channel.getContext().createArtifact(file.getInputStream(), finalName, null); }); // FIXME: this.service.createArtifact ( channelId, name, file.getInputStream (), null ); return redirectDefaultView(channelId, true); } catch (final Exception e) { return CommonController.createError("Upload", "Upload failed", e); } }
From source file:uk.ac.ncl.ssip.webserver.StartDBServlet.java
private void processFiles() throws IOException { String path = new File(".").getCanonicalPath() + "/target/webapp/uploads/"; System.out.println(path);//from w ww. ja va 2s . co m OutputStream out = null; InputStream filecontent = null; try { for (Part filePart : fileParts) { if (filePart.getName().contains("url")) { String[] urlSplit = request.getParameter(filePart.getName()).split("/"); if (urlSplit.length > 1) { System.out.println("URL detected: " + filePart.getName() + "\nFile name: " + urlSplit[urlSplit.length - 1]); FileUtils.copyURLToFile(new URL(request.getParameter(filePart.getName())), new File("./target/webapp/uploads/" + urlSplit[urlSplit.length - 1])); System.out.println("New file " + urlSplit[urlSplit.length - 1] + " created in uploads."); } } if (filePart.getName().contains("file")) { fileNum++; if (!getFileName(filePart).equals("")) { if (!(new File(path).list().toString().contains(getFileName(filePart)))) { out = new FileOutputStream(new File(path + File.separator + getFileName(filePart))); filecontent = filePart.getInputStream(); int read = 0; final byte[] bytes = new byte[1024]; while ((read = filecontent.read(bytes)) != -1) { out.write(bytes, 0, read); } //APPEND TO LOG FILE NOT CONSOLE System.out.println("New file " + getFileName(filePart) + " created at " + path); LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", new Object[] { getFileName(filePart), path }); } else { System.out.println("File already exists in uploads: " + getFileName(filePart)); } } } } } catch (FileNotFoundException fne) { System.out.println("You either did not specify a file to upload or are " + "trying to upload a file to a protected or nonexistent " + "location."); System.out.println("<br/> ERROR: " + fne.getMessage()); LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", new Object[] { fne.getMessage() }); } finally { if (out != null) { out.close(); } if (filecontent != null) { filecontent.close(); } } }