List of usage examples for org.springframework.web.multipart MultipartFile isEmpty
boolean isEmpty();
From source file:com.mmj.app.biz.service.impl.FileServiceImpl.java
public Result createFilePath(MultipartFile file, IFileCreate... ihandle) { // ?//from w ww . j av a 2s. c om if (file == null) { return Result.failed(); } if (!file.isEmpty()) { if (StringUtils.isEmpty(file.getOriginalFilename())) { return Result.failed(); } String[] suffixArray = StringUtils.split(file.getOriginalFilename(), "."); if (Argument.isEmptyArray(suffixArray)) { return Result.failed(); } String prefix = null; if (Argument.isEmptyArray(ihandle)) { prefix = SerialNumGenerator.Random30String(); } else { prefix = ihandle[0].build(SerialNumGenerator.Random30String(), ""); } String suffix = null; if (suffixArray.length == 1) { suffix = "jpg"; } else { suffix = suffixArray[1]; } String filePath = prefix + DELIMITER + suffix; // String filePath48 = prefix + "=48x48" + DELIMITER + suffix; try { // file.transferTo(new File(UPLOAD_TMP_PATH + filePath)); // FileUtils.copyFile(new File(UPLOAD_TMP_PATH + filePath), new File(UPLOAD_TMP_PATH + filePath48)); return Result.success(null, STATIC_TMP_IMG + filePath); } catch (Exception e) { logger.error(e.getMessage()); return Result.failed(); } } return Result.failed(); }
From source file:com.pantuo.service.impl.AttachmentServiceImpl.java
public String saveAttachmentSimple(HttpServletRequest request) throws BusinessException { StringBuffer r = new StringBuffer(); try {/*www. ja va 2 s .c o m*/ CustomMultipartResolver multipartResolver = new CustomMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { String path = request.getSession().getServletContext() .getRealPath(com.pantuo.util.Constants.FILE_UPLOAD_DIR).replaceAll("WEB-INF", ""); 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(); 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); if (r.length() == 0) { r.append(p.getRight()); } else { r.append(";" + p.getRight()); } } } } } return r.toString(); } catch (Exception e) { log.error("saveAttachmentSimple", e); throw new BusinessException("saveAttachment-error", e); } }
From source file:com.campodejazayeri.wedding.AdminController.java
@RequestMapping("/bulk-invite") public String bulkInvite(@RequestParam("invitees") MultipartFile invitees) throws Exception { if (!invitees.isEmpty()) { Map<String, InvitationGroup> groupsByName = new HashMap<String, InvitationGroup>(); ViewQuery query = new ViewQuery().designDocId("_design/groups").viewName("groups").includeDocs(true); for (InvitationGroup existing : db.queryView(query, InvitationGroup.class)) { groupsByName.put(standardizeName(existing.getGroupName()), existing); }// w ww . j av a 2 s .co m BufferedReader r = new BufferedReader(new InputStreamReader(invitees.getInputStream())); for (String row = r.readLine(); row != null; row = r.readLine()) { String[] cells = row.split(","); if (cells[0].equals("Group Name")) continue; if (!(StringUtils.hasText(cells[0]) && StringUtils.hasText(cells[1]) && StringUtils.hasText(cells[2]))) throw new RuntimeException("Malformed row: " + row); if (cells[0].startsWith("\"") && cells[0].endsWith("\"")) cells[0] = cells[0].substring(1, cells[0].length() - 1); InvitationGroup group = groupsByName.get(cells[0].trim()); if (group == null) { group = new InvitationGroup(); group.setGroupName(cells[0].trim()); throw new RuntimeException("Only updates now! Couldn't find " + cells[0]); } group.setEmail(cells[1].trim()); group.setLanguage(cells[2].trim()); group.setInvitedTours(StringUtils.hasText(cells[3])); group.setInvitedRehearsal(StringUtils.hasText(cells[4])); if (group.getInvitees() != null) group.getInvitees().clear(); for (int i = 5; i < cells.length; ++i) { if (StringUtils.hasText(cells[i].trim())) { Invitee invitee = new Invitee(); invitee.setName(cells[i].trim()); group.addInvitee(invitee); } } if (group.getInvitees().size() == 0) throw new RuntimeException("Group with no invitees: " + row); if (group.getId() == null) { group.setId(randomId()); db.create(group); System.out.println("Created " + group.getGroupName()); } else { db.update(group); System.out.println("Updated " + group.getId() + " " + group.getGroupName()); } } } return "redirect:admin"; }
From source file:com.indeed.iupload.web.controller.AppController.java
@RequestMapping(value = "/repository/{repoId}/index/{indexName}/file/", method = RequestMethod.POST) public @ResponseBody BasicResponse executeCreateFile(@PathVariable String repoId, @PathVariable String indexName, @RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception { if (!checkUserQualification(request, repoId, indexName)) { throw new UnauthorizedOperationException(); }/*from w w w . j a v a2 s . c om*/ if (file.isEmpty()) { return BasicResponse.error("File is not specified"); } IndexRepository repository = getRepository(repoId); Index index = repository.find(indexName); InputStream is = file.getInputStream(); try { index.createFileToIndex(file.getOriginalFilename(), is); } finally { Closeables2.closeQuietly(is, log); } return BasicResponse.success(null); }
From source file:com.trenako.web.controllers.RollingStocksController.java
@RequestMapping(method = RequestMethod.POST) public String create(@ModelAttribute @Valid RollingStockForm form, BindingResult bindingResult, ModelMap model, RedirectAttributes redirectAtts) { MultipartFile file = form.getFile(); RollingStock rs = form.buildRollingStock(valuesService, secContext, new Date()); if (bindingResult.hasErrors()) { model.addAttribute(rejectForm(form, valuesService)); return "rollingstock/new"; }/*from w w w . j av a2s . c o m*/ try { service.createNew(rs); if (!file.isEmpty()) { imgService.saveImageWithThumb(UploadRequest.create(rs, file), 100); } redirectAtts.addFlashAttribute("message", ROLLING_STOCK_CREATED_MSG); redirectAtts.addAttribute("slug", rs.getSlug()); return "redirect:/rollingstocks/{slug}"; } catch (DuplicateKeyException duplEx) { log.error(duplEx.toString()); model.addAttribute(newForm(rs, valuesService)); model.addAttribute("message", ROLLING_STOCK_DUPLICATED_VALUE_MSG); return "rollingstock/new"; } catch (DataAccessException dataEx) { log.error(dataEx.toString()); model.addAttribute(newForm(rs, valuesService)); model.addAttribute("message", ROLLING_STOCK_DATABASE_ERROR_MSG); return "rollingstock/new"; } }
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. j a v a 2 s .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:com.qcadoo.report.internal.controller.ReportDevelopmentController.java
@RequestMapping(value = "developReport/report", method = RequestMethod.POST) public ModelAndView uploadReportFile(@RequestParam("file") final MultipartFile file, final HttpServletRequest request) { if (!showReportDevelopment) { return new ModelAndView(new RedirectView("/")); }//from w w w. ja va 2 s .co m if (file.isEmpty()) { return new ModelAndView(L_QCADOO_REPORT_REPORT).addObject("isFileInvalid", true); } try { String template = IOUtils.toString(file.getInputStream()); List<ReportParameter> params = getReportParameters(template); return new ModelAndView(L_QCADOO_REPORT_REPORT).addObject(L_TEMPLATE, template) .addObject("isParameter", true).addObject(L_PARAMS, params).addObject(L_LOCALE, "en"); } catch (Exception e) { return showException(L_QCADOO_REPORT_REPORT, e); } }
From source file:com.emaxcore.emaxdata.modules.testdrive.pub.web.TestdriveUploadSignatureController.java
/** * ???????/*from www .j ava2 s .c o m*/ * * @param model * @param request * @param response * @return * @throws Exception */ @RequestMapping(value = "uploadSignature") @ResponseBody public String uploadSignature(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException { if (isDebugLogger) { logger.debug(" ??------uploadSignature-------start--------"); } response.setContentType(TestdrivePubConstant.ENCODED); Map<?, ?> jsonMap = null; // ? // ??????? StringBuilder idcardDriveProtocol = new StringBuilder(); // ??????? CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if (multipartResolver.isMultipart(request)) { MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // json String jsonDataStr = multiRequest.getParameter(TestdrivePubConstant.VALUE); if (Global.isSecretMode()) { if (isDebugLogger) { logger.debug("app ?---------- Start------{}---------", jsonDataStr); } AES256EncryptionUtils des = AES256EncryptionUtils.getInstance(); String jsonData = des.decrypt(jsonDataStr); jsonMap = JsonMapper.nonDefaultMapper().fromJson(jsonData, HashMap.class); } else { jsonMap = JsonMapper.nonDefaultMapper().fromJson(jsonDataStr, HashMap.class); } if (isDebugLogger) { logger.debug("uploadSignature?----------jsonMap---{}---------", jsonMap); } // ? TestDriveApplyInfo testDriveApplyInfo = new TestDriveApplyInfo(); //??-- String userFristName = TestdrivePubUtils.readJsonMapValue("fristName", jsonMap); if (StringUtils.isBlank(userFristName)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "fristName", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setFirstName(userFristName); //??-- String userLastName = TestdrivePubUtils.readJsonMapValue("lastName", jsonMap); if (StringUtils.isBlank(userLastName)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "lastName", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setLastName(userLastName); //?? String userName = userFristName + userLastName; testDriveApplyInfo.setName(userName); //telephone String telephone = TestdrivePubUtils.readJsonMapValue("telephone", jsonMap); if (StringUtils.isBlank(telephone)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "telephone", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setMobile(telephone); //appellation String appellation = TestdrivePubUtils.readJsonMapValue("appellation", jsonMap); if (StringUtils.isBlank(appellation)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "appellation", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setSex(appellation); //motorcycleType String motorcycleType = TestdrivePubUtils.readJsonMapValue("motorcycleType", jsonMap); if (StringUtils.isBlank(motorcycleType)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "motorcycleType", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setVehiclesType(motorcycleType); // String widthName = TestdrivePubUtils.readJsonMapValue("userName", jsonMap); if (StringUtils.isBlank(widthName)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "userName", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setWidthName(widthName); // ?MD5 String idCarMD5Hash = TestdrivePubUtils.readJsonMapValue("IDCarMD5Hash", jsonMap); // MD5 String driveMD5Hash = TestdrivePubUtils.readJsonMapValue("driveMD5Hash", jsonMap); // ????MD5 String protocolMD5Hash = TestdrivePubUtils.readJsonMapValue("protocolMD5Hash", jsonMap); // ??? String cidNumber = TestdrivePubUtils.readJsonMapValue("IDNumber", jsonMap); if (StringUtils.isBlank(cidNumber)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "???", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } testDriveApplyInfo.setIdNumber(cidNumber); // ?D:\apache-tomcat-7.0.47\webapps\benz String path = TestdrivePubUtils.getRealPath(request); // ????/mnt/sdc1/data/benzsite String savePath = Global.getUserfilesBaseDir(); // ?/userfiles/app/login ??login String signaturePicAddressPre = TestdrivePubConstant.APP_USER_FILES_PATH + userName; String filePath = ""; // /benz String projectPath = request.getContextPath(); if (StringUtils.isBlank(savePath)) { // ?D:\apache-tomcat-7.0.47\webapps\benz/userfiles/app/login filePath = path + signaturePicAddressPre; } else { filePath = savePath + projectPath + signaturePicAddressPre; } Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { MultipartFile file = multiRequest.getFile((String) iter.next()); if (file != null && !file.isEmpty()) { String fileName = file.getOriginalFilename(); FileEmaxDataUtils.createDirectory(filePath); String fileNamePath = filePath + File.separator + fileName; String relativePath = projectPath + signaturePicAddressPre + File.separator + fileName; File localFile = new File(fileNamePath); file.transferTo(localFile); String md5Hash = MD5Utils.getFileMD5String(localFile); // ? if (fileName.startsWith(TestdrivePubConstant.IDCARD_PREFIX)) { if (!idCarMD5Hash.equals(md5Hash)) { idcardDriveProtocol.append(card); boolean deletFlag = localFile.delete(); if (deletFlag) { logger.info("??"); } } else { testDriveApplyInfo.setIdentityCardScanningFile(relativePath); } } // if (fileName.startsWith(TestdrivePubConstant.DRIVE_PREFIX)) { if (!driveMD5Hash.equals(md5Hash)) { idcardDriveProtocol.append(drive); boolean deletFlag = localFile.delete(); if (deletFlag) { logger.info("?!"); } } else { testDriveApplyInfo.setDriversLicenseScanningFile(relativePath); } } // ???? if (fileName.startsWith(TestdrivePubConstant.PROTOCOL_PREFIX)) { if (!protocolMD5Hash.equals(md5Hash)) { idcardDriveProtocol.append(protocol); boolean deletFlag = localFile.delete(); if (deletFlag) { logger.info("?????"); } } else { testDriveApplyInfo.setNumberSignature(relativePath); } } } } // ????1?1? String driveStatus = testDriveApplyInfo.getDriveStatus(); if ((StringUtils.isNotBlank(driveStatus) && (Integer.parseInt(driveStatus) < 1)) || StringUtils.isBlank(driveStatus)) { testDriveApplyInfo.setDriveStatus("1");// ?? } testDriveApplyInfoService.save(testDriveApplyInfo); } else { jsonMap = this.saveJson(TestdrivePubConstant.SUCCESS_STATE, "??", ""); return TestdrivePubUtils.loggerJsonMap(jsonMap); } if (StringUtils.isNotBlank(idcardDriveProtocol)) { jsonMap = this.saveJson(TestdrivePubConstant.ERROR_STATE, "", idcardDriveProtocol.toString()); return TestdrivePubUtils.loggerJsonMap(jsonMap); } else { jsonMap = this.saveJson(TestdrivePubConstant.SUCCESS_STATE, TestdrivePubConstant.SUCCESS, idcardDriveProtocol.toString()); } String appJson = TestdrivePubUtils.loggerJsonMap(jsonMap); if (isDebugLogger) { logger.debug("??--uploadSignature----end---"); } return appJson; }
From source file:com.node.action.UserAction.java
private String uploadImg(HttpServletRequest request, MultipartFile file) throws FileNotFoundException, IOException { if (!file.isEmpty()) { PicPath imgPath = iCompanyService.getPathById(SystemConstants.PIC_IMG); String source = imgPath.getVcAddpath();// ? SimpleDateFormat format = new SimpleDateFormat("yyMMdd"); source = source + "/" + format.format(new Date()); if (!source.endsWith("/")) { source += "/"; }/*from w w w .java 2 s . c o m*/ if (StringUtils.isBlank(source)) { System.out.println("source??"); return null; } String getImagePath = source; // ??? String uploadName = file.getContentType(); System.out.println(" ------------" + uploadName); String lastuploadName = uploadName.substring(uploadName.indexOf("/") + 1, uploadName.length()); System.out.println("??? ------------" + lastuploadName); // ?? String fileNewName = generateFileName(file.getOriginalFilename()); System.out.println("// ?? ------------" + fileNewName); // ? String imagePath = source + "/" + fileNewName; System.out.println(" //? " + imagePath); File image = new File(getImagePath); if (!image.exists()) { image.mkdir(); } // file.transferTo(pathFile); BufferedImage srcBufferImage = ImageIO.read(file.getInputStream()); BufferedImage scaledImage; ScaleImage scaleImage = new ScaleImage(); int yw = srcBufferImage.getWidth(); int yh = srcBufferImage.getHeight(); int w = SystemConstants.IMG_LICENCE_WITH, h = SystemConstants.IMG_LICENCE_HEIGHT; if (w > yw && h > yh) { File image2 = new File(getImagePath, fileNewName); file.transferTo(image2); } else { scaledImage = scaleImage.imageZoomOut(srcBufferImage, w, h); FileOutputStream out = new FileOutputStream(getImagePath + "/" + fileNewName); ImageIO.write(scaledImage, "jpeg", out); out.close(); } return format.format(new Date()) + "/" + fileNewName;// ???? } else { return null; } }
From source file:de.interactive_instruments.etf.webapp.controller.TestObjectController.java
@RequestMapping(value = "/testobjects/add-file-to", method = RequestMethod.POST) public String addFileTestData(@ModelAttribute("testObject") @Valid TestObjectDto testObject, BindingResult result, MultipartHttpServletRequest request, Model model) throws IOException, URISyntaxException, StoreException, ParseException, NoSuchAlgorithmException { if (SUtils.isNullOrEmpty(testObject.getLabel())) { throw new IllegalArgumentException("Label is empty"); }/*from w ww. j a v a 2 s .com*/ if (result.hasErrors()) { return showCreateDoc(model, testObject); } final GmlAndXmlFilter filter; final String regex = testObject.getProperty("regex"); if (regex != null && !regex.isEmpty()) { filter = new GmlAndXmlFilter(new RegexFileFilter(regex)); } else { filter = new GmlAndXmlFilter(); } // Transfer uploaded data final MultipartFile multipartFile = request.getFile("testObjFile"); if (multipartFile != null && !multipartFile.isEmpty()) { // Transfer file to tmpUploadDir final IFile testObjFile = this.tmpUploadDir .secureExpandPathDown(testObject.getLabel() + "_" + multipartFile.getOriginalFilename()); testObjFile.expectFileIsWritable(); multipartFile.transferTo(testObjFile); final String type; try { type = MimeTypeUtils.detectMimeType(testObjFile); if (!type.equals("application/xml") && !type.equals("application/zip")) { throw new IllegalArgumentException(type + " is not supported"); } } catch (Exception e) { result.reject("l.upload.invalid", new Object[] { e.getMessage() }, "Unable to use file: {0}"); return showCreateDoc(model, testObject); } // Create directory for test data file final IFile testObjectDir = testDataDir .secureExpandPathDown(testObject.getLabel() + ".upl." + getSimpleRandomNumber(4)); testObjectDir.ensureDir(); if (type.equals("application/zip")) { // Unzip files to test directory try { testObjFile.unzipTo(testObjectDir, filter); } catch (IOException e) { try { testObjectDir.delete(); } catch (Exception de) { ExcUtils.supress(de); } result.reject("l.decompress.failed", new Object[] { e.getMessage() }, "Unable to decompress file: {0}"); return showCreateDoc(model, testObject); } finally { // delete zip file testObjFile.delete(); } } else { // Move XML to test directory testObjFile.copyTo(testObjectDir.getPath() + File.separator + multipartFile.getOriginalFilename()); } testObject.addResource("data", testObjectDir.toURI()); testObject.getProperties().setProperty("uploaded", "true"); } else { final URI resURI = testObject.getResourceById("data"); if (resURI == null) { throw new StoreException("Workflow error. Data path resource not set."); } final IFile absoluteTestObjectDir = testDataDir.secureExpandPathDown(resURI.getPath()); testObject.getResources().clear(); testObject.getResources().put(EidFactory.getDefault().createFromStrAsStr("data"), absoluteTestObjectDir.toURI()); // Check if file exists final IFile sourceDir = new IFile(new File(testObject.getResourceById("data"))); try { sourceDir.expectDirIsReadable(); } catch (Exception e) { result.reject("l.testObject.testdir.insufficient.rights", new Object[] { e.getMessage() }, "Insufficient rights to read directory: {0}"); return showCreateDoc(model, testObject); } testObject.getProperties().setProperty("uploaded", "false"); } final FileHashVisitor v = new FileHashVisitor(filter); Files.walkFileTree(new File(testObject.getResourceById("data")).toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), 5, v); if (v.getFileCount() == 0) { if (regex != null && !regex.isEmpty()) { result.reject("l.testObject.regex.null.selection", new Object[] { regex }, "No files were selected with the regular expression \"{0}\"!"); } else { result.reject("l.testObject.testdir.no.xml.gml.found", "No file were found in the directory with a gml or xml file extension"); } return showCreateDoc(model, testObject); } VersionDataDto vd = new VersionDataDto(); vd.setItemHash(v.getHash()); testObject.getProperties().setProperty("files", String.valueOf(v.getFileCount())); testObject.getProperties().setProperty("size", String.valueOf(v.getSize())); testObject.getProperties().setProperty("sizeHR", FileUtils.byteCountToDisplaySize(v.getSize())); testObject.setVersionData(vd); testObject.setId(EidFactory.getDefault().createRandomUuid()); testObjStore.create(testObject); return "redirect:/testobjects"; }