List of usage examples for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE
String MULTIPART_FORM_DATA_VALUE
To view the source code for org.springframework.http MediaType MULTIPART_FORM_DATA_VALUE.
Click Source Link
From source file:com.company.project.web.controller.FileUploadController.java
@RequestMapping(value = "/asyncUpload2", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody/* www.ja va 2 s .co m*/ public ResponseEntity<String> asyncFileUpload2(HttpServletRequest request) throws Exception { MultipartHttpServletRequest mpr = (MultipartHttpServletRequest) request; if (request instanceof MultipartHttpServletRequest) { CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("fileUpload"); List<MultipartFile> fs = (List<MultipartFile>) mpr.getFiles("fileUpload"); System.out.println("f: " + f); for (String key : mpr.getParameterMap().keySet()) { System.out.println("Param Key: " + key + "\n Value: " + mpr.getParameterMap().get(key)); } for (String key : mpr.getMultiFileMap().keySet()) { System.out.println("xParam Key: " + key + "\n xValue: " + mpr.getMultiFileMap().get(key)); } } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); Map<String, Object> parameterMap = new HashMap<>(); Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields"); //if(request.getContentType().contains("multipart/form-data")){ if (ServletFileUpload.isMultipartContent(request)) { Map<String, Object> map = new HashMap<>(); List<FileItem> filefields = new ArrayList<>(); List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { //contentType: "image/jpeg", isFormField: false, fileName: "Chrysanthemum.jpg" if (item.isFormField()) { formfields.put(item.getFieldName(), item.getString()); } else { filefields.add(item); } } parameterMap.put("filefields", filefields); } return new ResponseEntity<>("success", HttpStatus.OK); }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * API endpoint to import a file or list of files as a new layer or layers into GeoServer. * Files are provided as MediaType.MULTIPART_FORM_DATA_VALUE in the request * @param wsName The workspace to import the files into * @param request The HTTP request/*from w w w . j av a2 s.c o m*/ * @return a JSON object describing the result of the import. See {@link #get(String, Long) get}. * @throws Exception if the request is invalid, or the file upload fails. */ @RequestMapping(value = "/{wsName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseBody JSONObj importFile(@PathVariable String wsName, HttpServletRequest request) throws Exception { return importFile(wsName, null, request); }
From source file:com.github.cherimojava.orchidae.controller.PictureController.java
/** * uploads multiple files into the system for the current user * //w ww . j av a2 s. c o m * @param request * request with pictures to store * @return {@link org.springframework.http.HttpStatus#CREATED} if the upload was successful or * {@link org.springframework.http.HttpStatus#OK} if some of the pictures couldn't be uploaded together with * information which pictures couldn't be uploaded * @since 1.0.0 */ @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<String> handleFileUpload(MultipartHttpServletRequest request) { List<String> badFiles = Lists.newArrayList(); User user = userUtil .getUser((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal()); for (Iterator<String> it = request.getFileNames(); it.hasNext();) { MultipartFile file = request.getFile(it.next()); // Create uuid and Picture entity Picture picture = factory.create(Picture.class); picture.setUser(user); picture.setTitle(StringUtils.split(file.getOriginalFilename(), ".")[0]); picture.setId(generateId()); picture.setOriginalName(file.getOriginalFilename()); picture.setUploadDate(DateTime.now()); String type = StringUtils.substringAfterLast(file.getOriginalFilename(), "."); try { File storedPicture = fileUtil.getFileHandle(picture.getId()); // save picture file.transferTo(storedPicture); // read some some properties from it BufferedImage image = ImageIO.read(storedPicture); picture.setHeight(image.getHeight()); picture.setWidth(image.getWidth()); picture.setAccess(Access.PRIVATE);// TODO for now only private access createSmall(picture.getId(), image, type); LOG.info("Uploaded {} and assigned id {}", file.getOriginalFilename(), picture.getId()); checkBatch(picture, request); picture.save(); } catch (Exception e) { LOG.warn("failed to store picture", e); badFiles.add(file.getOriginalFilename()); } } if (badFiles.isEmpty()) { return new ResponseEntity<>("You successfully uploaded!", HttpStatus.CREATED); } else { return new ResponseEntity<>( "Could not upload all files. Failed to upload: " + Joiner.on(",").join(badFiles), HttpStatus.OK); } }
From source file:de.unimannheim.spa.process.rest.ProjectRestControllerTest.java
@Test public void itShouldReturn500ForCreatingAProcessWithUnsopportedFormat() throws Exception { expected.expect(NestedServletException.class); final String projectIDForTest = createProjectAndReturnID(); final String processLabelToTest = "newProcessLabelToTest"; final String unsupportedFormat = "TXT"; MockMultipartFile processFileToTest = new MockMultipartFile("processFile", "example-spa.bpmn", MediaType.MULTIPART_FORM_DATA_VALUE, Files.toByteArray(getFilePath("example-spa.bpmn").toFile())); mockMvc.perform(fileUpload("/projects/" + projectIDForTest + "/processes").file(processFileToTest) .param("processLabel", processLabelToTest).param("format", unsupportedFormat)) .andExpect(status().isInternalServerError()); }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * API endpoint to import a file or list of files as a new layer or layers into into an existing * store inGeoServer. /*from ww w . ja va 2 s.c o m*/ * Files are provided as MediaType.MULTIPART_FORM_DATA_VALUE in the request * @param wsName The workspace to import the files into * @param storeName The store to import the layers into. If null, tries to import into a new * store. * @param request The HTTP request * @return a JSON object describing the result of the import. See {@link #get(String, Long) get}. * @throws Exception if the request is invalid, or the file upload fails. */ @RequestMapping(value = "/{wsName:.+}/{storeName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseBody JSONObj importFile(@PathVariable String wsName, @PathVariable String storeName, HttpServletRequest request) throws Exception { // grab the workspace Catalog catalog = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, catalog); // get the uploaded files FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain one or more files"); } // create a new temp directory for the uploaded file File uploadDir = Files.createTempDirectory("importFile").toFile(); if (!uploadDir.exists()) { throw new RuntimeException("Unable to create directory for file upload"); } uploadDir.deleteOnExit(); // pass off the uploaded file(s) to the importer Directory dir = new Directory(uploadDir); while (files.hasNext()) { FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { String name = item.getName(); dir.accept(name, stream); } } Long id; if (storeName == null) { id = importer.createContextAsync(dir, ws, null); } else { StoreInfo store = findStore(wsName, storeName, geoServer.getCatalog()); id = importer.createContextAsync(dir, ws, store); } return get(wsName, createImport(importer.getTask(id)), request); }
From source file:com.boundlessgeo.geoserver.api.controllers.WorkspaceController.java
@RequestMapping(value = "/{wsName}/import", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseStatus(value = HttpStatus.OK)//from w w w . j a v a 2s.co m public void inport(@PathVariable String wsName, HttpServletRequest request, HttpServletResponse response) throws Exception { Catalog cat = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, cat); // grab the uploaded file FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain a single file"); } Path zip = Files.createTempFile(null, null); FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { IOUtils.copy(stream, zip.toFile()); } BundleImporter importer = new BundleImporter(cat, new ImportOpts(ws)); importer.unzip(zip); importer.run(); }
From source file:com.traffitruck.web.HtmlController.java
@RequestMapping(value = "/newload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) ModelAndView newLoad(@ModelAttribute("load") Load load, BindingResult br1, @RequestParam("loadPhoto") byte[] loadPhoto, BindingResult br2, @RequestParam("drivedate") String drivedate, BindingResult br3, @RequestParam("sourceLat") Double sourceLat, BindingResult br4, @RequestParam("sourceLng") Double sourceLng, BindingResult br5, @RequestParam("destinationLat") Double destinationLat, BindingResult br6, @RequestParam("destinationLng") Double destinationLng, BindingResult br7) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); load.setCreationDate(new Date()); try {/*w w w . j ava2 s . c o m*/ load.setDriveDate(sdf.parse(drivedate)); } catch (ParseException e) { throw new RuntimeException(e); } Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); load.setUsername(username); if (loadPhoto != null && loadPhoto.length > 0) { load.setLoadPhoto(new Binary(loadPhoto)); } if (sourceLat != null && sourceLng != null) { load.setSourceLocation(new Location(new double[] { sourceLng, sourceLat })); } if (destinationLat != null && destinationLng != null) { load.setDestinationLocation(new Location(new double[] { destinationLng, destinationLat })); } dao.storeLoad(load); asyncServices.triggerAlerts(load); return new ModelAndView("redirect:/myLoads"); }
From source file:net.gbmb.collector.RecordController.java
@RequestMapping(value = "/records/{cid}/attach", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public void recordWithAttachment(@PathVariable("cid") String cid, @RequestParam("record") byte[] recordb, @RequestParam("attached") byte[] attached) throws CollectionStateException { CollectionRecord record = null;/* w w w.ja va 2s .com*/ try { record = convertFromB64(new ByteArrayInputStream(recordb)); } catch (IOException e) { throw new CollectRuntimeException("Failed to convert body to record", e); } // check if collection exists if (!collectionMap.containsKey(cid)) { // collection not existing throw new CollectionStateException("Collection not existing"); } // check if record is valid if (!recordValidator.validate(record)) { // record not valid throw new IllegalArgumentException("Record is invalid"); } // store attachment try { String contentId = temporaryStorage.store(cid, new ByteArrayInputStream(attached)); record.setAttachment(contentId); addRecord(cid, record); } catch (IOException e) { throw new CollectRuntimeException("Failed to save the attached file", e); } }
From source file:com.traffitruck.web.HtmlController.java
@RequestMapping(value = "/updateload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) ModelAndView updateLoad(@ModelAttribute("load") Load load, BindingResult br1, @RequestParam("loadPhoto") byte[] loadPhoto, BindingResult br2, @RequestParam("drivedate") String drivedate, BindingResult br3, @RequestParam("sourceLat") Double sourceLat, BindingResult br4, @RequestParam("sourceLng") Double sourceLng, BindingResult br5, @RequestParam("destinationLat") Double destinationLat, BindingResult br6, @RequestParam("destinationLng") Double destinationLng, BindingResult br7, @RequestParam("loadId") String loadId, BindingResult br8) throws IOException, HttpMediaTypeNotAcceptableException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yy"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); try {//from w ww.j a v a 2 s .c om load.setDriveDate(sdf.parse(drivedate)); } catch (ParseException e) { throw new RuntimeException(e); } load.setId(loadId); Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); load.setUsername(username); if (loadPhoto != null && loadPhoto.length > 0) { load.setLoadPhoto(new Binary(loadPhoto)); } if (sourceLat != null && sourceLng != null) { load.setSourceLocation(new Location(new double[] { sourceLng, sourceLat })); } if (destinationLat != null && destinationLng != null) { load.setDestinationLocation(new Location(new double[] { destinationLng, destinationLat })); } Load oldLoad = dao.getLoadForUserById(loadId, username); if (oldLoad == null) { throw new ConversionNotSupportedException(null, null, null); } // update the load dao.updateLoad(load); asyncServices.triggerAlerts(load); return new ModelAndView("redirect:/myLoads"); }