List of usage examples for org.springframework.web.multipart MultipartFile getName
String getName();
From source file:org.shaf.server.controller.CmdActionController.java
/** * Puts data to the server.//from w w w .j a va2 s.c o m * * @param storage * the storage type. * @param alias * the data alias. * @param data * the data to upload. * @throws NetworkContentException * @throws Exception * if an error occurs. */ @RequestMapping(value = "/upload/{storage}/{alias}", method = RequestMethod.POST) public void onUpload(@PathVariable String storage, @PathVariable String alias, @RequestBody MultipartFile data) throws Exception { LOG.debug("CALL service: /cmd/upload/{" + storage + "}/{" + alias + "} with attached data."); LOG.trace("The attached data: " + data); if (data.isEmpty()) { LOG.warn("There no providing data."); } else { Firewall firewall = super.getFirewall(); String username = super.getUserName(); StorageDriver driver = OPER.getStorageDriver(firewall, username, StorageType.PROVIDER, storage); LOG.trace("Driver for uploading: " + driver); LOG.trace("Uploading data name: " + data.getName()); LOG.trace("Uploading data size: " + data.getSize()); try (InputStream in = data.getInputStream(); OutputStream out = driver.getOutputStream(alias)) { ByteStreams.copy(in, out); } catch (IOException exc) { throw exc; } } }
From source file:net.nan21.dnet.core.web.controller.upload.FileUploadController.java
/** * Generic file upload. Expects an uploaded file and a handler alias to * delegate the uploaded file processing. * /* w w w . j a va 2 s .c o m*/ * @param handler * spring bean alias of the * {@link net.nan21.dnet.core.api.service.IFileUploadService} * which should process the uploaded file * @param file * Uploaded file * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/{handler}", method = RequestMethod.POST) @ResponseBody public String fileUpload(@PathVariable("handler") String handler, @RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception { if (logger.isInfoEnabled()) { logger.info("Processing file upload request with-handler {} ", new String[] { handler }); } if (file.isEmpty()) { throw new Exception("Upload was not succesful. Try again please."); } this.prepareRequest(request, response); IFileUploadService srv = this.getFileUploadService(handler); Map<String, String> paramValues = new HashMap<String, String>(); for (String p : srv.getParamNames()) { paramValues.put(p, request.getParameter(p)); } IUploadedFileDescriptor fileDescriptor = new UploadedFileDescriptor(); fileDescriptor.setContentType(file.getContentType()); fileDescriptor.setOriginalName(file.getOriginalFilename()); fileDescriptor.setNewName(file.getName()); fileDescriptor.setSize(file.getSize()); Map<String, Object> result = srv.execute(fileDescriptor, file.getInputStream(), paramValues); this.finishRequest(); result.put("success", true); ObjectMapper mapper = getJsonMapper(); return mapper.writeValueAsString(result); }
From source file:seava.j4e.web.controller.upload.FileUploadController.java
/** * Generic file upload. Expects an uploaded file and a handler alias to * delegate the uploaded file processing. * //from www . j a v a 2s. c o m * @param handler * spring bean alias of the * {@link seava.j4e.api.service.IFileUploadService} which should * process the uploaded file * @param file * Uploaded file * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "/{handler}", method = RequestMethod.POST) @ResponseBody public String fileUpload(@PathVariable("handler") String handler, @RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception { try { if (logger.isInfoEnabled()) { logger.info("Processing file upload request with-handler {} ", new Object[] { handler }); } if (file.isEmpty()) { throw new BusinessException(ErrorCode.G_FILE_NOT_UPLOADED, "Upload was not succesful. Try again please."); } this.prepareRequest(request, response); IFileUploadService srv = this.getFileUploadService(handler); Map<String, String> paramValues = new HashMap<String, String>(); for (String p : srv.getParamNames()) { paramValues.put(p, request.getParameter(p)); } IUploadedFileDescriptor fileDescriptor = new UploadedFileDescriptor(); fileDescriptor.setContentType(file.getContentType()); fileDescriptor.setOriginalName(file.getOriginalFilename()); fileDescriptor.setNewName(file.getName()); fileDescriptor.setSize(file.getSize()); Map<String, Object> result = srv.execute(fileDescriptor, file.getInputStream(), paramValues); result.put("success", true); ObjectMapper mapper = getJsonMapper(); return mapper.writeValueAsString(result); } catch (Exception e) { return this.handleManagedException(null, e, response); } finally { this.finishRequest(); } }
From source file:kr.co.exsoft.external.controller.ExternalPublicController.java
@RequestMapping(value = "/restful.singleUpload", method = RequestMethod.POST) @ResponseBody//ww w. jav a 2 s . c o m public String singleFileUploadTest(@RequestParam("uploadBox") MultipartFile file) { // <input type="file" name="uploadBox"> String name = "File not found"; if (!file.isEmpty()) { try { name = file.getName(); byte[] bytes = file.getBytes(); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(name + "-uploaded"))); stream.write(bytes); stream.close(); return "You successfully uploaded " + name + " into " + name + "-uploaded !"; } 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:org.shareok.data.webserv.PlosWebController.java
@RequestMapping(value = "/plos/upload", method = RequestMethod.POST) public ModelAndView plosUpload(@RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { try {/*from w ww . j av a 2 s. com*/ byte[] bytes = file.getBytes(); // Creating the directory to store file // String rootPath = System.getProperty("catalina.home"); // File dir = new File(rootPath + File.separator + "tmpFiles"); // if (!dir.exists()) // dir.mkdirs(); // // // Create the file on server // File serverFile = new File(dir.getAbsolutePath() // + File.separator + name); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(serverFile)); // stream.write(bytes); // stream.close(); // logger.info("Server File Location=" // + serverFile.getAbsolutePath()); System.out.println("The uploaded file name is " + file.getName() + "\n"); ModelAndView model = new ModelAndView(); model.setViewName("plosDataUpload"); model.addObject("message", file.getOriginalFilename()); return model; } catch (Exception e) { e.printStackTrace(); } } else { return null; } return null; }
From source file:gov.gtas.services.CaseDispositionServiceImpl.java
/** * Utility method to persist attachment to each case comment * @param file// w w w . j av a2 s .c o m * @param _tempHitsDispComments * @throws Exception */ private void populateAttachmentsToCase(MultipartFile file, HitsDispositionComments _tempHitsDispComments, Long pax_id) throws Exception { Attachment attachment = new Attachment(); //Build attachment to be added to pax Set<Attachment> _tempAttachSet = new HashSet<Attachment>(); if (_tempHitsDispComments.getAttachmentSet() != null) _tempAttachSet = _tempHitsDispComments.getAttachmentSet(); attachment.setContentType(file.getContentType()); attachment.setFilename(file.getOriginalFilename()); attachment.setName(file.getName()); byte[] bytes = file.getBytes(); Blob blob = new javax.sql.rowset.serial.SerialBlob(bytes); attachment.setContent(blob); //Grab pax to add attachment to it Passenger pax = passengerRepository.findOne(pax_id); attachment.setPassenger(pax); attachmentRepository.save(attachment); _tempAttachSet.add(attachment); _tempHitsDispComments.setAttachmentSet(_tempAttachSet); }
From source file:com.glaf.core.web.springmvc.MxUploadController.java
@RequestMapping("/uploadNow") public ModelAndView upload(HttpServletRequest request, ModelMap modelMap) { LoginContext loginContext = RequestUtils.getLoginContext(request); MultipartHttpServletRequest req = (MultipartHttpServletRequest) request; String type = req.getParameter("type"); if (StringUtils.isEmpty(type)) { type = "0"; }/*from ww w. jav a 2s. c o m*/ String serviceKey = req.getParameter("serviceKey"); if (StringUtils.isEmpty(serviceKey)) { modelMap.put("error_message", "????serviceKey?"); return new ModelAndView("/error"); } Map<String, Object> paramMap = RequestUtils.getParameterMap(req); logger.debug("paramMap:" + paramMap); String businessKey = req.getParameter("businessKey"); String objectId = req.getParameter("objectId"); String objectValue = req.getParameter("objectValue"); int status = ParamUtils.getInt(paramMap, "status"); List<DataFile> dataFiles = new java.util.ArrayList<DataFile>(); try { semaphore.acquire(); if (StringUtils.isNotEmpty(businessKey)) { List<DataFile> rows = blobService.getBlobList(businessKey); if (rows != null && rows.size() > 0) { dataFiles.addAll(rows); } } paramMap.remove("businessKey"); paramMap.put("createBy", loginContext.getActorId()); paramMap.put("serviceKey", serviceKey); paramMap.put("status", status); BlobItemQuery query = new BlobItemQuery(); Tools.populate(query, paramMap); query.createBy(loginContext.getActorId()); query.serviceKey(serviceKey); query.status(status); List<DataFile> rows = blobService.getBlobList(query); if (rows != null && rows.size() > 0) { Iterator<DataFile> iterator = rows.iterator(); while (iterator.hasNext()) { DataFile dataFile = iterator.next(); if (!dataFiles.contains(dataFile)) { dataFiles.add(dataFile); } } } Map<String, MultipartFile> fileMap = req.getFileMap(); Set<Entry<String, MultipartFile>> entrySet = fileMap.entrySet(); for (Entry<String, MultipartFile> entry : entrySet) { MultipartFile mFile = entry.getValue(); if (mFile.getOriginalFilename() != null && mFile.getSize() > 0) { String filename = mFile.getOriginalFilename(); logger.debug("upload file:" + filename); String fileId = UUID32.getUUID(); if (filename.indexOf("/") != -1) { filename = filename.substring(filename.lastIndexOf("/") + 1, filename.length()); } else if (filename.indexOf("\\") != -1) { filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length()); } BlobItem dataFile = new BlobItemEntity(); dataFile.setLastModified(System.currentTimeMillis()); dataFile.setCreateBy(loginContext.getActorId()); dataFile.setFileId(fileId); dataFile.setData(mFile.getBytes()); dataFile.setFilename(filename); dataFile.setName(mFile.getName()); dataFile.setContentType(mFile.getContentType()); dataFile.setSize((int) mFile.getSize()); dataFile.setType(type); dataFile.setStatus(status); dataFile.setObjectId(objectId); dataFile.setObjectValue(objectValue); dataFile.setServiceKey(serviceKey); blobService.insertBlob(dataFile); dataFile.setData(null); dataFiles.add(dataFile); } } if (dataFiles.size() > 0) { modelMap.put("dataFiles", dataFiles); } } catch (Exception ex) { logger.debug(ex); return new ModelAndView("/error"); } finally { semaphore.release(); } return this.showUpload(request, modelMap); }
From source file:architecture.ee.web.spring.controller.SecureWebMgmtDataController.java
@RequestMapping(value = "/mgmt/logo/upload.json", method = RequestMethod.POST) @ResponseBody// www. j a v a 2 s . co m public Result uploadLogoImage( @RequestParam(value = "objectType", defaultValue = "1", required = false) Integer objectType, @RequestParam(value = "objectId", defaultValue = "0", required = false) Long objectId, MultipartHttpServletRequest request) throws NotFoundException, IOException { User user = SecurityHelper.getUser(); if (objectId == 0) { if (objectType == 1) { objectId = user.getCompanyId(); } else if (objectType == 30) { objectId = WebSiteUtils.getWebSite(request).getWebSiteId(); } } Iterator<String> names = request.getFileNames(); while (names.hasNext()) { String fileName = names.next(); log.debug(fileName); MultipartFile mpf = request.getFile(fileName); InputStream is = mpf.getInputStream(); log.debug("file name: " + mpf.getOriginalFilename()); log.debug("file size: " + mpf.getSize()); log.debug("file type: " + mpf.getContentType()); log.debug("file class: " + is.getClass().getName()); LogoImage logo = logoManager.createLogoImage(); logo.setFilename(mpf.getName()); logo.setImageContentType(mpf.getContentType()); logo.setImageSize((int) mpf.getSize()); logo.setObjectType(objectType); logo.setObjectId(objectId); logo.setPrimary(true); logoManager.addLogoImage(logo, mpf.getInputStream()); } return Result.newResult(); }
From source file:it.geosolutions.opensdi.operations.OperationEngineController.java
/** * Obtain a temporal file item with chunked bytes * //from w ww . j ava 2s . c o m * @param file * @param chunkedBytes * @param name * @return */ private FileItem getFileItem(MultipartFile file, List<byte[]> chunkedBytes, String name) { // Temporal file to write chunked bytes File outFile = FileUtils.getFile(FileUtils.getTempDirectory(), name); // total file size int sizeThreshold = 0; for (byte[] bytes : chunkedBytes) { sizeThreshold += bytes.length; } // Get file item FileItem fileItem = new DiskFileItem("tmpFile", file.getContentType(), false, name, sizeThreshold, outFile); try { OutputStream outputStream; outputStream = fileItem.getOutputStream(); // write bytes for (byte[] readedBytes : chunkedBytes) { outputStream.write(readedBytes, 0, readedBytes.length); } // close the file outputStream.flush(); outputStream.close(); } catch (IOException e) { LOGGER.error("Error writing final file", e); } finally { // Remove bytes from memory uploadedChunks.remove(file.getName()); } return fileItem; }
From source file:ua.aits.sdolyna.controller.SystemController.java
@RequestMapping(value = { "/Sdolyna/uploadFile", "/uploadFile", "/Sdolyna/uploadFile/", "/uploadFile/" }, method = RequestMethod.POST) public @ResponseBody String uploadFileHandlerFull(@RequestParam("upload") MultipartFile file, @RequestParam("path") String path, HttpServletRequest request) { Integer curent = Integer.parseInt(Helpers.lastFileModified(Constants.home + path).getName().split("\\.")[0]) + 1;//from ww w . ja v a2 s. c o m String ext = file.getOriginalFilename().split("\\.")[1]; String name = curent.toString() + "." + ext; 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 "<img class=\"main-img\" src=\"" + Constants.URL + link_path + "\" realpath='" + link_path + "' alt='" + link_path + file.getName() + "' />"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } } else { return "You failed to upload " + name + " because the file was empty."; } }