List of usage examples for org.springframework.web.multipart MultipartFile getOriginalFilename
@Nullable String getOriginalFilename();
From source file:com.denimgroup.threadfix.importer.loader.ScanTypeCalculationServiceImpl.java
private String getScannerType(MultipartFile file) { String fullFilePath = getFilePath(); saveFile(fullFilePath, file);/*from w w w.j a v a 2 s . c om*/ String returnValue = getScannerType(file.getOriginalFilename(), fullFilePath); deleteFile(fullFilePath); if (REMOTE_PROVIDERS.contains(returnValue)) { throw new RestIOException("Import " + returnValue + " scans using the Remote Provider functionality.", -1); } return returnValue; }
From source file:com.tela.pms.PatientController.java
public File convertFile(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); convFile.createNewFile();/*from ww w .j ava 2 s .c o m*/ FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; }
From source file:org.gallery.web.controller.ImageController.java
@RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody Map upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException { log.info("UploadPost called..."); Iterator<String> itr = request.getFileNames(); MultipartFile mpf; List<ImageVO> list = new LinkedList<>(); while (itr.hasNext()) { mpf = request.getFile(itr.next()); String originalFilename = mpf.getOriginalFilename(); if (originalFilename == null || StringUtils.isEmpty(originalFilename)) { originalFilename = UUID.randomUUID().toString() + ".jpg"; }/*from w w w .j a va 2 s. co m*/ log.info("Uploading {}", originalFilename); String newFilenameBase = "-" + UUID.randomUUID().toString(); String storageDirectory = fileUploadDirectory; String contentType = mpf.getContentType(); if (contentType == null || StringUtils.isEmpty(contentType)) { contentType = "image/jpeg"; } String newFilename = newFilenameBase; InputStream in = null; try { // Save Images // mpf.transferTo(newFile); in = new ByteArrayInputStream(mpf.getBytes()); BufferedImage originalImage = ImageIO.read(in); // Save Original Image String filenameExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length()); ImageIO.write(originalImage, filenameExtension, new File(storageDirectory + File.separatorChar + originalFilename)); // Small Thumbnails BufferedImage thumbnail_small = Scalr.resize(originalImage, ThumbnailSize.SMALL_SIZE.getSize()); compressImg(thumbnail_small, new File(storageDirectory + File.separatorChar + ThumbnailSize.SMALL_SIZE.getId() + newFilenameBase + "." + ThumbnailSize.SMALL_SIZE.getFormatName()), ThumbnailSize.SMALL_SIZE.getCompressionQuality()); // Medium Thumbnail BufferedImage thumbnail_medium = Scalr.resize(originalImage, ThumbnailSize.MEDIUM_SIZE.getSize()); compressImg(thumbnail_medium, new File(storageDirectory + File.separatorChar + ThumbnailSize.MEDIUM_SIZE.getId() + newFilenameBase + "." + ThumbnailSize.MEDIUM_SIZE.getFormatName()), ThumbnailSize.MEDIUM_SIZE.getCompressionQuality()); // Big Thumbnails BufferedImage thumbnail_big = Scalr.resize(originalImage, ThumbnailSize.BIG_SIZE.getSize()); compressImg(thumbnail_big, new File(storageDirectory + File.separatorChar + ThumbnailSize.BIG_SIZE.getId() + newFilenameBase + "." + ThumbnailSize.BIG_SIZE.getFormatName()), ThumbnailSize.BIG_SIZE.getCompressionQuality()); log.info("EmotionParser..."); // ImageEntity entity = // EmotionParser.parse(ImageIO.read(newFile)); ImageEntity entity = new ImageEntity(); entity.setName(originalFilename); entity.setNewFilename(newFilename); entity.setContentType(contentType); entity.setSize(mpf.getSize()); imageDao.save(entity); ImageVO imageVO = new ImageVO(entity); imageVO.setId(entity.getId()); imageVO.setUrl("/picture/" + entity.getId()); imageVO.setThumbnailUrl("/thumbnail/" + entity.getId()); imageVO.setDeleteUrl("/delete/" + entity.getId()); imageVO.setEmotionUrl("/emotion/" + entity.getId()); imageVO.setDeleteType("DELETE"); list.add(imageVO); } catch (IOException e) { log.error("Could not upload file " + originalFilename, e); } finally { in.close(); } } Map<String, Object> files = new HashMap<>(); files.put("files", list); return files; }
From source file:com.pantuo.service.impl.AttachmentServiceImpl.java
@Override public String savePayvoucher(HttpServletRequest request, String user_id, int main_id, JpaAttachment.Type file_type, String description) throws BusinessException { String result = ""; try {//from www . ja v a 2 s . c om CustomMultipartResolver multipartResolver = new CustomMultipartResolver( request.getSession().getServletContext()); log.info("userid:{},main_id:{},file_type:{}", user_id, main_id, file_type); if (multipartResolver.isMultipart(request)) { String path = request.getSession().getServletContext() .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", ""); log.info("path=", path); MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile(iter.next()); if (file != null && !file.isEmpty()) { String oriFileName = file.getOriginalFilename(); String fn = file.getName(); if (StringUtils.isNoneBlank(oriFileName)) { String storeName = GlobalMethods .md5Encrypted((System.currentTimeMillis() + oriFileName).getBytes()); Pair<String, String> p = FileHelper.getUploadFileName(path, storeName += FileHelper.getFileExtension(oriFileName, true)); File localFile = new File(p.getLeft()); file.transferTo(localFile); AttachmentExample example = new AttachmentExample(); AttachmentExample.Criteria criteria = example.createCriteria(); criteria.andMainIdEqualTo(main_id); criteria.andUserIdEqualTo(user_id); criteria.andTypeEqualTo(JpaAttachment.Type.payvoucher.ordinal()); List<Attachment> attachments = attachmentMapper.selectByExample(example); if (attachments.size() > 0) { Attachment t = attachments.get(0); t.setUpdated(new Date()); t.setName(oriFileName); t.setUrl(p.getRight()); attachmentMapper.updateByPrimaryKey(t); result = p.getRight(); } else { Attachment t = new Attachment(); if (StringUtils.isNotBlank(description)) { t.setDescription(description); } t.setMainId(main_id); t.setType(file_type.ordinal()); t.setCreated(new Date()); t.setUpdated(t.getCreated()); t.setName(oriFileName); t.setUrl(p.getRight()); t.setUserId(user_id); attachmentMapper.insert(t); result = p.getRight(); } } } } } } catch (Exception e) { log.error("saveAttachment", e); throw new BusinessException("saveAttachment-error", e); } return result; }
From source file:cn.lhfei.fu.service.impl.ThesisBaseServiceImpl.java
@Override public boolean update(ThesisBaseModel model, String userType) throws Exception { OutputStream out = null;/* w ww . j av a2 s .c o m*/ BufferedOutputStream bf = null; Date currentTime = new Date(); boolean result = false; List<MultipartFile> files = model.getFiles(); try { boolean modelIsValid = this.updateThesis(model); if (!modelIsValid) { return result; } int num = 1; for (MultipartFile file : files) {// save archive file if (file.getSize() > 0) { String filePath = filePathBuilder.buildThesisFullPath(model, model.getStudentName()); String fileName = filePathBuilder.buildThesisFileName(model, model.getStudentName(), num); String[] names = file.getOriginalFilename().split("[.]"); String fileType = names[names.length - 1]; String fullPath = filePath + File.separator + fileName + "." + fileType; out = new FileOutputStream(new File(fullPath)); bf = new BufferedOutputStream(out); IOUtils.copyLarge(file.getInputStream(), bf); ThesisArchive archive = new ThesisArchive(); archive.setThesisBaseId(model.getBaseId()); archive.setStudentId(model.getStudentId()); archive.setArchiveName(fileName); archive.setArchivePath(fullPath); archive.setCreateTime(currentTime); archive.setModifyTime(currentTime); archive.setStudentBaseId(model.getStudentBaseId()); archive.setThesisTitle(model.getThesisTitle()); archive.setExtend(model.getThesisEnTitle()); // archive.setExtend1(model.getThesisType()); // // ? if (userType != null && userType.equals(UserTypeEnum.STUDENT.getCode())) { archive.setStatus("" + ApproveStatusEnum.DSH.getCode()); } else if (userType != null && userType.equals(UserTypeEnum.TEACHER.getCode())) { archive.setStatus("" + ApproveStatusEnum.DSH.getCode()); } else if (userType != null && userType.equals(UserTypeEnum.ADMIN.getCode())) { archive.setStatus("" + ApproveStatusEnum.YSH.getCode()); } thesisArchiveDAO.save(archive); // auto increment archives number. num++; } } result = true; } catch (IOException e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage(), e); } catch (NullPointerException e) { log.error("File name arguments missed.", e); throw new NullPointerException(e.getMessage()); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } if (bf != null) { try { bf.flush(); bf.close(); } catch (IOException e) { log.error(e.getMessage(), e); } } } return result; }
From source file:com.sc.service.SaleService.java
/** * /*from www.j a va 2 s .com*/ * * @param userId * @param phone * @param address * @param lon * @param lat * @param pwd * @param cardno * @param companyname * @param personname * @param contactname * @param contactphone * @param telephone * @param pax * @param cardFiles * @param storeFiles * @param licenseFiles * @return */ public Result SellerApplication(String userId, Long phone, String address, Double lon, Double lat, String pwd, String cardno, String companyname, String personname, String contactname, String contactphone, String telephone, String pax, MultipartFile[] cardFiles, MultipartFile[] storeFiles, MultipartFile[] licenseFiles) { try { Admins admins = saleDao.getAdminByAdminId(userId); if (admins == null || (admins.getCM_LEVEL() != 2 && admins.getCM_LEVEL() != 1)) { return GetResult.toJson(45, null, null, null, 0); } //?? int n = saleDao.getSellerCount(phone); if (n > 0) { return GetResult.toJson(60, null, null, null, 0); } //check seller cardno int m = saleDao.getSellerCount(cardno); if (m > 0) { return GetResult.toJson(64, null, null, null, 0); } String card = ""; String store = ""; String license = ""; String Date = DateUtils.todayYyyyMmDdHhMmSs(); for (MultipartFile file : cardFiles) { int i = 0; String fileName = file.getOriginalFilename(); if (!storageService.isImage(fileName)) { return GetResult.toJson(28, null, null, null, 0); } String res = ""; String newfilename = root + "sellers\\" + Date + "\\" + "card\\" + i + "." + storageService.getFileType(fileName); if (storageService.store(file, newfilename)) { res = "C://Applications/sellers/" + Date + "/card/" + i + "." + storageService.getFileType(fileName); } card += res + "|"; i++; } for (MultipartFile file : storeFiles) { int i = 0; String fileName = file.getOriginalFilename(); if (!storageService.isImage(fileName)) { return GetResult.toJson(28, null, null, null, 0); } String res = ""; String newfilename = root + "sellers\\" + Date + "\\" + "store\\" + i + "." + storageService.getFileType(fileName); if (storageService.store(file, newfilename)) { res = "C://Applications/sellers/" + Date + "/store/" + i + "." + storageService.getFileType(fileName); } store += res + "|"; i++; } for (MultipartFile file : licenseFiles) { int i = 0; String fileName = file.getOriginalFilename(); if (!storageService.isImage(fileName)) { return GetResult.toJson(28, null, null, null, 0); } String res = ""; String newfilename = root + "sellers\\" + Date + "\\" + "license\\" + i + "." + storageService.getFileType(fileName); if (storageService.store(file, newfilename)) { res = "C://Applications/sellers/" + Date + "/license/" + i + "." + storageService.getFileType(fileName); } license += res + "|"; i++; } Long act = saleDao.getSellerMaxAccount(); String account = String.valueOf(act + 1).replace("4", "5"); Sellers sellers = new Sellers(); sellers.setCM_ACCOUNT(account); sellers.setCM_CREATETIME(new Date()); sellers.setCM_ISEXAMINE(0); sellers.setCM_CARDPATH(card); sellers.setCM_STOREPATH(store); sellers.setCM_LICENSEPATH(license); sellers.setCM_PHONE(phone); sellers.setCM_PASSWORD(pwd); sellers.setCM_ADDRESS(address); sellers.setCM_SELLERID(DateUtils.todayYyyyMmDdHhMmSs()); sellers.setCM_SELLERNAME(companyname); sellers.setCM_LAT(lat); sellers.setCM_LON(lon); sellers.setCM_CARDNO(cardno); sellers.setCM_NAME(personname); sellers.setCM_CONTACTNAME(contactname); sellers.setCM_CONTACTPHONE(contactphone); sellers.setCM_TELEPHONE(telephone); sellers.setCM_PAX(pax); sellers.setCM_REASON(userId); saleDao.sellerApplication(sellers); return GetResult.toJson(0, null, jwt.createJWT(userId), account, 0); } catch (Exception e) { return GetResult.toJson(200, null, null, null, 0); } }
From source file:org.opentestsystem.authoring.testauth.rest.ScoringRuleController.java
@ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = "/scoringRule/conversionTableFile/{type}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.TEXT_PLAIN_VALUE) @Secured({ "ROLE_Scoring Rule Modify" }) // NOTE: there is intentionally no @PreAuthorize annotation...ability to modify scoring rule is all that is needed since scoring rule conversion table files are non-tenanted @ResponseBody/*from w ww . ja va2 s . co m*/ public String uploadConversionTableFile( @RequestParam("conversionTableFile") final MultipartFile conversionTableFile, @PathVariable("type") final String type, final HttpServletRequest request, final HttpServletResponse response) throws IOException { String jsonAsStringForIE = null; try { final GridFSFile savedFile = this.scoringRuleService.saveConversionTableFile(type, conversionTableFile.getOriginalFilename(), conversionTableFile.getBytes(), conversionTableFile.getContentType()); jsonAsStringForIE = savedFile.toString(); } catch (final LocalizedException e) { // return a 201 here - // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e)); } catch (final IOException e) { // return a 201 here - // IE9 and browsers which require iframe transport must receive an OK status to get the response result after file upload jsonAsStringForIE = this.objectMapper.writeValueAsString(super.handleException(e)); } return jsonAsStringForIE; }
From source file:gt.dakaik.rest.impl.UserImpl.java
@Override public ResponseEntity<String> handleFileUpload(Long idUser, MultipartFile file) throws EntidadNoEncontradaException { User u = repoU.findOne(idUser);/*from w w w . jav a 2s . co m*/ if (u != null) { if (!file.isEmpty()) { try { File convFile = new File(file.getOriginalFilename()); convFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); CompressImages cImage = new CompressImages(convFile, "img"); List<File> files = cImage.getFamilyFixedProcessedFiles(); System.out.println(files.size() + " files to upload."); //************ String SFTPHOST = "www.colegios.e.gt"; int SFTPPORT = 1157; String SFTPUSER = "colegiose"; String SFTPPASS = "Dario2015."; String SFTPWORKINGDIR = "/home/colegiose/public_html/images/u/"; String PARENT_PATH = "" + idUser; SFTPinJava.saveFileToSftp(files, false, SFTPHOST, SFTPPORT, SFTPUSER, SFTPPASS, SFTPWORKINGDIR, PARENT_PATH); //************ u.setTxtImageURI("http://www.colegios.e.gt/images/u/" + idUser + "/"); repoU.save(u); return new ResponseEntity(u.getTxtImageURI(), HttpStatus.OK); } catch (Exception e) { e.getMessage(); throw new EntidadNoEncontradaException(); } } else { throw new EntidadNoEncontradaException(); } } else { throw new EntidadNoEncontradaException("User"); } }
From source file:eu.scidipes.toolkits.pawebapp.web.AdminController.java
@RequestMapping(value = "/templates", method = RequestMethod.POST) public String saveTemplate(final RedirectAttributes redirectAttrs, final String processorName, @RequestPart(value = "source") final MultipartFile sourceFile) { final PreservationDatasourceProcessor processor = SourceProcessorManager.INSTANCE.getProcessors() .get(processorName);// ww w.j a v a 2 s . c om final StringBuilder destinationPath = new StringBuilder(); destinationPath.append(SOURCE_ROOT_PATH + File.separatorChar); destinationPath.append(processor.getClass().getSimpleName() + File.separatorChar); destinationPath.append(sourceFile.getOriginalFilename()); final File destination = new File(destinationPath.toString()); if (destination.exists()) { redirectAttrs.addFlashAttribute("errorKey", SAVE_FAIL_FILE_EXISTS); return "redirect:/admin/templates/"; } try { sourceFile.transferTo(destination); final FormsBundle bundle = processor.sourceToBundle(destination); ((FormsBundleImpl) bundle).setTemplateSource(destination.getName()); FormBundleManager.addBundle(bundle); LOG.info("Created new template bundle for processor: {}", processor.getName()); } catch (final IOException | PreservationException e) { LOG.warn("Exception encountered creating bundle from: {}, deleting file: {}.", destination, Boolean.valueOf(destination.delete())); LOG.error(e.toString(), e); redirectAttrs.addFlashAttribute("errorKey", SAVE_FAIL); return "redirect:/admin/templates/"; } redirectAttrs.addFlashAttribute("msgKey", SAVE_SUCCESS); return "redirect:/admin/templates/"; }
From source file:com.sc.service.SaleService.java
/** * //w w w.ja v a 2s . co m * * @param userId * @param phone * @param address * @param lon * @param lat * @param pwd * @param cardno * @param shopname * @param personname * @param contactname * @param contactphone * @param telephone * @param pax * @param cardFiles * @param storeFiles * @param licenseFiles * @return */ public Result UserApplication(String userId, Long phone, String address, Double lon, Double lat, String pwd, String cardno, String shopname, String personname, String contactname, String contactphone, String telephone, String pax, MultipartFile[] cardFiles, MultipartFile[] storeFiles, MultipartFile[] licenseFiles) { try { Admins admins = saleDao.getAdminByAdminId(userId); if (admins == null || (admins.getCM_LEVEL() != 2 && admins.getCM_LEVEL() != 1)) { return GetResult.toJson(45, null, null, null, 0); } //?? int n = saleDao.getUserCount(phone); if (n > 0) { return GetResult.toJson(60, null, null, null, 0); } //check user cardno int m = saleDao.getUserCount(cardno); if (m > 0) { return GetResult.toJson(64, null, null, null, 0); } String card = ""; String store = ""; String license = ""; String Date = DateUtils.todayYyyyMmDdHhMmSs(); for (MultipartFile file : cardFiles) { int i = 0; String fileName = file.getOriginalFilename(); if (!storageService.isImage(fileName)) { return GetResult.toJson(28, null, null, null, 0); } String res = ""; String newfilename = root + "users\\" + Date + "\\" + "card\\" + i + "." + storageService.getFileType(fileName); if (storageService.store(file, newfilename)) { res = "C://Applications/users/" + Date + "/card/" + i + "." + storageService.getFileType(fileName); } card += res + "|"; i++; } for (MultipartFile file : storeFiles) { int i = 0; String fileName = file.getOriginalFilename(); if (!storageService.isImage(fileName)) { return GetResult.toJson(28, null, null, null, 0); } String res = ""; String newfilename = root + "users\\" + Date + "\\" + "store\\" + i + "." + storageService.getFileType(fileName); if (storageService.store(file, newfilename)) { res = "C://Applications/users/" + Date + "/store/" + i + "." + storageService.getFileType(fileName); } store += res + "|"; i++; } for (MultipartFile file : licenseFiles) { int i = 0; String fileName = file.getOriginalFilename(); if (!storageService.isImage(fileName)) { return GetResult.toJson(28, null, null, null, 0); } String res = ""; String newfilename = root + "users\\" + Date + "\\" + "license\\" + i + "." + storageService.getFileType(fileName); if (storageService.store(file, newfilename)) { res = "C://Applications/users/" + Date + "/license/" + i + "." + storageService.getFileType(fileName); } license += res + "|"; i++; } Long act = saleDao.getUserMaxAccount(); String account = String.valueOf(act + 1).replace("4", "5"); Users users = new Users(); users.setCM_USERID(DateUtils.todayYyyyMmDdHhMmSs()); users.setCM_ACCOUNT(account); users.setCM_BALANCE((double) 0); users.setCM_CREATETIME(new Date()); users.setCM_INTEGRAL(0); users.setCM_ISEXAMINE(0); users.setCM_LEVEL(0); users.setCM_CARDPATH(card); users.setCM_STOREPATH(store); users.setCM_LICENSEPATH(license); users.setCM_PHONE(phone); users.setCM_PASSWORD(pwd); users.setCM_SHOPEADDRESS(address); users.setCM_SHOPNAME(shopname); users.setCM_SHOPLAT(lat); users.setCM_SHOPLON(lon); users.setCM_CARDNO(cardno); users.setCM_NAME(personname); users.setCM_CONTACTNAME(contactname); users.setCM_CONTACTPHONE(contactphone); users.setCM_TELEPHONE(telephone); users.setCM_PAX(pax); users.setCM_REASON(userId); saleDao.userApplication(users); return GetResult.toJson(0, null, jwt.createJWT(userId), account, 0); } catch (Exception e) { return GetResult.toJson(200, null, null, null, 0); } }