List of usage examples for org.springframework.web.multipart MultipartFile getInputStream
@Override
InputStream getInputStream() throws IOException;
From source file:com.codestudio.dorm.web.support.spring.upload.FileUploadSupport.java
/** * /*from w ww . j a v a2 s. c om*/ * * @param file * @param type * @return */ public Attachment upload(long userId, MultipartFile file, String type) { if (StringUtils.isBlank(type)) { type = DEFAULT_TYPE; } FileOutputStream fs = null; InputStream is = null; if (file == null) { return null; } try { is = file.getInputStream(); String orgFileName = file.getOriginalFilename(); int i = orgFileName.lastIndexOf('.'); String ext = ""; if (i > 0) { ext = orgFileName.substring(i); } Date now = new Date(); String filePath = "/" + type + "/" + DateUtils.dateConvert2String(now, DateUtils.DATEPATTERN_YYYY_MM_DD4FILE) + "/"; String fileName = now.getTime() + "" + ((int) (Math.random() * 10)); File f = new File(uploadFilePath + filePath); if (!f.exists()) { f.mkdirs(); } fs = new FileOutputStream(uploadFilePath + filePath + fileName + ext); byte[] buffer = new byte[1024 * 1024]; int byteread = 0; while ((byteread = is.read(buffer)) != -1) { fs.write(buffer, 0, byteread); fs.flush(); } // ??? Attachment attachment = new Attachment(); attachment.setSrcName(file.getOriginalFilename()); attachment.setDescName(fileName); attachment.setFileType(type); attachment.setExt(ext); attachment.setPath(filePath); attachment.setSize(file.getSize()); attachment.setUserId(userId); attachmentService.add(attachment); return attachment; } catch (Exception e) { logger.error("upload file error:", e); } finally { try { fs.close(); is.close(); } catch (Exception e) { logger.error("close file error:", e); } } return null; }
From source file:de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.RemoteApiController.java
/** * Create a new project./* w w w . j a v a2 s .c om*/ * * To test, use the Linux "curl" command. * * curl -v -F 'file=@test.zip' -F 'name=Test' -F 'filetype=tcf' * 'http://USERNAME:PASSWORD@localhost:8080/de.tudarmstadt.ukp.clarin.webanno.webapp/api/project * ' * * @param aName * the name of the project to create. * @param aFileType * the type of the files contained in the ZIP. The possible file types are configured * in the formats.properties configuration file of WebAnno. * @param aFile * a ZIP file containing the project data. * @throws Exception if there was en error. */ @RequestMapping(value = "/project", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseStatus(HttpStatus.NO_CONTENT) void createProject(@RequestParam("file") MultipartFile aFile, @RequestParam("name") String aName, @RequestParam("filetype") String aFileType) throws Exception { LOG.info("Creating project [" + aName + "]"); if (!ZipUtils.isZipStream(aFile.getInputStream())) { throw new InvalidFileNameException("", "is an invalid Zip file"); } // Get current user String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); Project project = null; // Configure project if (!projectRepository.existsProject(aName)) { project = new Project(); project.setName(aName); // Create the project and initialize tags projectRepository.createProject(project, user); annotationService.initializeTypesForProject(project, user, new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {}, new String[] {}); // Create permission for this user ProjectPermission permission = new ProjectPermission(); permission.setLevel(PermissionLevel.ADMIN); permission.setProject(project); permission.setUser(username); projectRepository.createProjectPermission(permission); permission = new ProjectPermission(); permission.setLevel(PermissionLevel.USER); permission.setProject(project); permission.setUser(username); projectRepository.createProjectPermission(permission); } // Existing project else { throw new IOException("The project with name [" + aName + "] exists"); } // Iterate through all the files in the ZIP // If the current filename does not start with "." and is in the root folder of the ZIP, // import it as a source document File zimpFile = File.createTempFile(aFile.getOriginalFilename(), ".zip"); aFile.transferTo(zimpFile); ZipFile zip = new ZipFile(zimpFile); for (Enumeration<?> zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) { // // Get ZipEntry which is a file or a directory // ZipEntry entry = (ZipEntry) zipEnumerate.nextElement(); // If it is the zip name, ignore it if ((FilenameUtils.removeExtension(aFile.getOriginalFilename()) + "/").equals(entry.toString())) { continue; } // IF the current filename is META-INF/webanno/source-meta-data.properties store it // as // project meta data else if (entry.toString().replace("/", "") .equals((META_INF + "webanno/source-meta-data.properties").replace("/", ""))) { InputStream zipStream = zip.getInputStream(entry); projectRepository.savePropertiesFile(project, zipStream, entry.toString()); } // File not in the Zip's root folder OR not // META-INF/webanno/source-meta-data.properties else if (StringUtils.countMatches(entry.toString(), "/") > 1) { continue; } // If the current filename does not start with "." and is in the root folder of the // ZIP, import it as a source document else if (!FilenameUtils.getExtension(entry.toString()).equals("") && !FilenameUtils.getName(entry.toString()).equals(".")) { uploadSourceDocument(zip, entry, project, user, aFileType); } } LOG.info("Successfully created project [" + aName + "] for user [" + username + "]"); }
From source file:org.openmrs.module.radiology.web.controller.RadiologyObsFormController.java
/** * Open input stream for complex data file * /* w w w. ja v a2s .co m*/ * @param complexDataFile the complex data file * @return input stream for complex data file * @throws IOException if stream could not be opened * @should open input stream for complex data file * @should throw exception if input stream could not be opened */ private InputStream openInputStreamForComplexDataFile(MultipartFile complexDataFile) throws IOException { if (complexDataFile == null) { throw new IOException("error.general"); } return complexDataFile.getInputStream(); }
From source file:com.qcadoo.model.internal.file.FileServiceImpl.java
@Override public String upload(final MultipartFile multipartFile) throws IOException { File file = getFileFromFilenameWithRandomDirectory(multipartFile.getOriginalFilename()); OutputStream output = null;//w w w . jav a 2 s . c o m try { output = new FileOutputStream(file); IOUtils.copy(multipartFile.getInputStream(), output); } catch (IOException e) { LOG.error(e.getMessage(), e); IOUtils.closeQuietly(output); throw e; } return file.getAbsolutePath(); }
From source file:org.openmrs.web.controller.observation.ObsFormController.java
/** * Sets the value of a complex obs from an http request. * * @param obs the complex obs whose value to set. * @param request the http request./*from ww w.j a v a2s . c om*/ * @return the complex data input stream. */ private InputStream setComplexData(Obs obs, HttpServletRequest request) throws IOException { InputStream complexDataInputStream = null; if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile complexDataFile = multipartRequest.getFile("complexDataFile"); if (complexDataFile != null && !complexDataFile.isEmpty()) { complexDataInputStream = complexDataFile.getInputStream(); ComplexData complexData = new ComplexData(complexDataFile.getOriginalFilename(), complexDataInputStream); obs.setComplexData(complexData); } } return complexDataInputStream; }
From source file:com.hs.mail.web.controller.WebConsole.java
private ModelAndView doImportAccounts(WebSession session) { MultipartHttpServletRequest multi = (MultipartHttpServletRequest) session.getRequest(); DataImporter importer = new DataImporter(); MultipartFile mf = multi.getFile("file"); if (mf != null) { try {/*from w ww.j a v a2 s.c o m*/ session.removeBeans(WebSession.ACCOUNT_COUNT); importer.importAccount(manager, mf.getInputStream()); } catch (IOException e) { importer.addError(0, mf.getOriginalFilename(), e); } } if (importer.hasErrors()) { return new ModelAndView("importerror", "errors", importer.getErrors()); } else { return getRedirectView(session); } }
From source file:com.vmware.appfactory.datastore.DsDatastoreCifs.java
@Override public void copy(MultipartFile source, String destination, ProgressListener pl) throws IOException { /* Create destination file */ File destFile = new File(destination); /* Open input and output, for copying */ InputStream is = source.getInputStream(); OutputStream os = new FileOutputStream(destFile); try {//from w w w .j a v a2 s .co m /* We could use IOUtils.copy(), but this approach gives us progress: */ long total = source.getSize(); long soFar = 0; /* Transfer using a buffer */ byte[] buffer = new byte[COPY_BUFFER_SIZE]; int numRead; while ((numRead = is.read(buffer, 0, COPY_BUFFER_SIZE)) != -1) { os.write(buffer, 0, numRead); soFar += numRead; if (pl != null) { pl.update(soFar, total, 1); } } os.flush(); } finally { os.close(); is.close(); } }
From source file:eu.freme.eservices.epublishing.ServiceRestController.java
@RequestMapping(value = "/e-publishing/html", method = RequestMethod.POST) public ResponseEntity<byte[]> htmlToEPub(@RequestParam("htmlZip") MultipartFile file, @RequestParam("metadata") String jMetadata) throws IOException, InvalidZipException, EPubCreationException, MissingMetadataException { Gson gson = new Gson(); Metadata metadata = gson.fromJson(jMetadata, Metadata.class); MultiValueMap<String, String> headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_TYPE, "Application/epub+zip"); try (InputStream in = file.getInputStream()) { return new ResponseEntity<>(epubAPI.createEPUB(metadata, in), headers, HttpStatus.OK); }//from w w w .jav a 2 s . c o m }
From source file:com.funtl.framework.smoke.core.modules.act.service.ActProcessService.java
/** * ? - ?/*from w w w. ja va2s . c om*/ * * @param file * @return */ @Transactional(readOnly = false) public String deploy(String exportDir, String category, MultipartFile file) { String message = ""; String fileName = file.getOriginalFilename(); try { InputStream fileInputStream = file.getInputStream(); Deployment deployment = null; String extension = FilenameUtils.getExtension(fileName); if (extension.equals("zip") || extension.equals("bar")) { ZipInputStream zip = new ZipInputStream(fileInputStream); deployment = repositoryService.createDeployment().addZipInputStream(zip).deploy(); } else if (extension.equals("png")) { deployment = repositoryService.createDeployment().addInputStream(fileName, fileInputStream) .deploy(); } else if (fileName.indexOf("bpmn20.xml") != -1) { deployment = repositoryService.createDeployment().addInputStream(fileName, fileInputStream) .deploy(); } else if (extension.equals("bpmn")) { // bpmn????bpmn20.xml String baseName = FilenameUtils.getBaseName(fileName); deployment = repositoryService.createDeployment() .addInputStream(baseName + ".bpmn20.xml", fileInputStream).deploy(); } else { message = "??" + extension; } List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery() .deploymentId(deployment.getId()).list(); // ? for (ProcessDefinition processDefinition : list) { // ActUtils.exportDiagramToFile(repositoryService, processDefinition, exportDir); repositoryService.setProcessDefinitionCategory(processDefinition.getId(), category); message += "??ID=" + processDefinition.getId() + "<br/>"; } if (list.size() == 0) { message = "?"; } } catch (Exception e) { throw new ActivitiException("?", e); } return message; }
From source file:com.healthcit.cacure.web.controller.FormExportController.java
@RequestMapping(method = RequestMethod.POST) public ModelAndView importForm(@RequestParam("file") MultipartFile file, @RequestParam("moduleId") long moduleId, HttpServletRequest request, HttpServletResponse response) { try {//w w w. ja v a2s .c o m if (file != null) { Map<String, String> existingForms = new HashMap<String, String>(); List<String> existingQuestions = new ArrayList<String>(); InputStream is = file.getInputStream(); JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model"); Unmarshaller m = jc.createUnmarshaller(); Cure cure = (Cure) m.unmarshal(is); dataImporter.importData(cure, moduleId, existingForms, existingQuestions); if (existingForms.size() > 0 || existingQuestions.size() > 0) { ModelAndView mav = new ModelAndView("formUploadStatus"); // initialize with view name ModelMap model = mav.getModelMap(); model.addAttribute("existingForms", existingForms); model.addAttribute("existingQuestions", existingQuestions); return mav; /* there had been errors */ // return new ModelAndView("formUploadStatus", "existingForms", existingForms); } } return new ModelAndView("formUploadStatus", "status", "OK"); } catch (Exception e) { log.error(e.getMessage(), e); return new ModelAndView("formUploadStatus", "status", "FAIL"); } }