List of usage examples for org.springframework.web.multipart.commons CommonsMultipartFile getOriginalFilename
@Override
public String getOriginalFilename()
From source file:com.gbcom.system.controller.SysInfoController.java
/** * ?//from ww w .java 2s . c o m * * @param request * HttpServletRequest * @param uploadFile * CommonsMultipartFile * @param response * HttpServletResponse */ @RequestMapping public void recovery(HttpServletRequest request, @RequestParam(value = "upFile", required = true) CommonsMultipartFile uploadFile, HttpServletResponse response) { String fileName = uploadFile.getOriginalFilename(); try { if (fileName == null || fileName.trim().equals("")) { sendFailureJSON(response, "????"); return; } String fileIp = fileName.substring(fileName.indexOf("-") + 1, fileName.lastIndexOf("-")); LinkedHashMap<String, String> ipMap = CmUtil.getLocalAddress(); if (!ipMap.containsKey(fileIp)) { sendFailureJSON(response, "????!"); return; } } catch (Exception e1) { sendFailureJSON(response, "????!"); return; } String realPath = request.getSession().getServletContext().getRealPath("/upload"); boolean isSuccess = false; File file = new File(realPath, fileName); try { FileUtils.copyInputStreamToFile(uploadFile.getInputStream(), file); String filePath = realPath + File.separator + uploadFile.getOriginalFilename(); // ? final SqlImportManager sqlService = new SqlImportManager(); isSuccess = sqlService.importSql(filePath); } catch (Exception e) { super.processException(response, e); } finally { try { file.delete(); } catch (Exception e) { } } if (!isSuccess) { sendFailureJSON(response, "?"); } else { sendSuccessJSON(response, "??"); } }
From source file:lcn.module.oltp.web.common.base.MultipartResolver.java
/** * multipart? parsing? ./*from w w w . jav a 2s . com*/ */ @SuppressWarnings("unchecked") @Override protected MultipartParsingResult parseFileItems(List fileItems, String encoding) { //? 3.0 MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>(); // Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); // Map multipartFiles = new HashMap(); Map multipartParameters = new HashMap(); // Extract multipart files and multipart parameters. for (Iterator it = fileItems.iterator(); it.hasNext();) { FileItem fileItem = (FileItem) it.next(); if (fileItem.isFormField()) { String value = null; if (encoding != null) { try { value = fileItem.getString(encoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + encoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } } else { if (fileItem.getSize() > 0) { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); //? 3.0 ? API? List<MultipartFile> fileList = new ArrayList<MultipartFile>(); fileList.add(file); if (multipartFiles.put(fileItem.getName(), fileList) != null) { // CHANGED!! throw new MultipartException("Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver"); } if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } } return new MultipartParsingResult((MultiValueMap<String, MultipartFile>) multipartFiles, (Map<String, String[]>) multipartParameters, multipartParameters); // return new MultipartParsingResult(multipartFiles, multipartParameters); }
From source file:com.msds.km.reparifacoty.controller.DrivingLicenseController.java
protected File saveFile(CommonsMultipartFile file, HttpServletRequest request) { SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH"); /** ? **///w ww. jav a 2s. co m String logoPathDir = "/files" + dateformat.format(new Date()); String contextPath = request.getSession().getServletContext().getRealPath("/"); /** ? **/ // String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir); String sep = System.getProperty("file.separator"); if (contextPath.endsWith(sep)) { contextPath = contextPath.substring(0, contextPath.length() - 1); } String logoRealPathDir = contextPath.substring(0, contextPath.lastIndexOf(sep)) + logoPathDir; /** ? **/ File logoSaveFile = new File(logoRealPathDir); if (!logoSaveFile.exists()) logoSaveFile.mkdirs(); /** ?? **/ String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); /** UUID??? **/ String logImageName = UUID.randomUUID().toString() + suffix; /** ?? **/ String fileName = logoRealPathDir + File.separator + logImageName; File savedFile = new File(fileName); try { file.transferTo(savedFile); return savedFile; } catch (IllegalStateException e) { throw new RecognitionException(e); } catch (IOException e) { throw new RecognitionException(e); } }
From source file:com.hp.avmon.discovery.service.DiscoveryService.java
/** * MIB/*w w w .ja v a 2 s .c o m*/ * * @param request * @return * @throws IOException */ public String importMibFile(HttpServletRequest request) throws IOException { String result = StringUtil.EMPTY; HashMap<String, ArrayList<Map<String, String>>> resultMap = new HashMap<String, ArrayList<Map<String, String>>>(); ArrayList<Map<String, String>> files = new ArrayList<Map<String, String>>(); String typeId = request.getParameter("typeId"); String deviceName = request.getParameter("deviceName"); String deviceDesc = request.getParameter("deviceDesc"); String factory = request.getParameter("factory"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // ? String templatePath = Config.getInstance().getMibfilesUploadPath(); File dirPath = new File(templatePath); if (!dirPath.exists()) { dirPath.mkdirs(); } Map<String, String> fileMap; for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) { String fileName = (String) it.next(); fileMap = new HashMap<String, String>(); CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(fileName); if (file != null && file.getSize() != 0) { String sep = System.getProperty("file.separator"); File uploadedFile = new File(dirPath + sep + file.getOriginalFilename()); FileCopyUtils.copy(file.getBytes(), uploadedFile); try { insertMibFileTb(file.getOriginalFilename(), typeId, deviceName, deviceDesc, factory); MibFileParserDB mibFileParser = new MibFileParserDB(dirPath + sep + file.getOriginalFilename()); mibFileParser.parseMib(jdbcTemplate); } catch (MibLoaderException e) { fileMap.put("error", "Mib"); logger.error(e.getMessage()); } catch (DataAccessException e1) { logger.error(e1.getMessage()); fileMap.put("error", "??,?"); } catch (Exception e2) { logger.error(this.getClass().getName() + e2.getMessage()); fileMap.put("error", ",?"); } } fileMap.put("url", ""); fileMap.put("thumbnailUrl", ""); fileMap.put("name", file.getOriginalFilename()); fileMap.put("type", "image/jpeg"); fileMap.put("size", file.getSize() + ""); fileMap.put("deleteUrl", ""); fileMap.put("deleteType", "DELETE"); files.add(fileMap); } resultMap.put("files", files); result = JackJson.fromObjectToJson(resultMap); logger.debug(result); return result; }
From source file:com.eliteams.pay.web.controller.RegisterController.java
@RequestMapping("/uploadmethod") @ResponseBody/*ww w. ja va2 s . c om*/ public String uploadmethod(HttpServletRequest request, HttpServletResponse response) throws IOException { Map<String, Object> rtnMap = new HashMap<String, Object>(); // String urlString = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() // + request.getContextPath() + "/pay/papersPhoto/"; String newRealFileName = null; String ftype = request.getParameter("ftype"); try { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; CommonsMultipartFile file = null; // String filetype = "businessLicense";//? if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 1) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField1"); } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 2) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField2"); /// filetype = "idCard";//? } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 3) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField3"); // filetype = "taxRegistration";// } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 4) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField4"); /// filetype = "proxy";// } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 5) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField5"); /// filetype = "file53";//? } if (ftype != null && !ftype.equals("") && Integer.valueOf(ftype) == 6) { file = (CommonsMultipartFile) multipartRequest.getFile("fileField6"); // filetype = "file6";//?? } if (file == null) { rtnMap.put("info", ""); return JSONUtil.map2json(rtnMap); } // ?? String realFileName = file.getOriginalFilename(); if (realFileName == null || "".equals(realFileName)) { rtnMap.put("info", ""); return JSONUtil.map2json(rtnMap); } String suffixFlag = realFileName.substring(realFileName.indexOf(".")); suffixFlag = suffixFlag.toLowerCase(); newRealFileName = new Date().getTime() + "." + FilenameUtils.getExtension(realFileName); /** * ???? */ if (!suffixFlag.contains("jpg") && !suffixFlag.contains("bmp") && !suffixFlag.contains("jpeg") && !suffixFlag.contains("gif") && !suffixFlag.contains("tiff") && !suffixFlag.contains("psd") && !suffixFlag.contains("tga") && !suffixFlag.contains("png") && !suffixFlag.contains("eps")) { rtnMap.put("info", "?"); return JSONUtil.map2json(rtnMap); } /** * :? */ byte[] bt = new byte[4]; bt = Arrays.copyOf(file.getBytes(), 4); String str = ImageTypeCheck.getPicType(bt); if (str != null) { if (str.contains("noimg")) { rtnMap.put("info", "???:jpg?jpeg?png?gif?bmp"); return JSONUtil.map2json(rtnMap); } } else { rtnMap.put("info", "?"); return JSONUtil.map2json(rtnMap); } /** *:? ? */ /*Image img= ImageIO.read( file.getInputStream()); img.getWidth(null);*/ // ? // String ctxPath = request.getSession().getServletContext().getRealPath("//") + "//pay//papersPhoto//" + "//"; // // String ctxPath = request.getScheme() + "://" + request.getLocalAddr() + ":" + request.getLocalPort() // + photopath; String ctxPath = realdownloadpath + photopath; logger.info("" + ctxPath); // File dirPath = new File(uploadpath); if (!dirPath.exists()) { dirPath.mkdir(); } File uploadFile = new File(uploadpath + newRealFileName); FileCopyUtils.copy(file.getBytes(), uploadFile); rtnMap.put("info", "?"); rtnMap.put("fileurl", ctxPath + newRealFileName); rtnMap.put("FileName", newRealFileName); // } } catch (Exception e) { e.printStackTrace(); logger.error(" ", e); rtnMap.put("info", ""); } return JSONUtil.map2json(rtnMap); }
From source file:org.asqatasun.webapp.validator.AddScenarioFormValidator.java
/** * /* w w w . ja va 2 s.c om*/ * @param addScenarioCommand * @param errors * @return whether the scenario handled by the current AddScenarioCommand * has a correct type and size */ public boolean checkScenarioFileTypeAndSize(AddScenarioCommand addScenarioCommand, Errors errors) { if (addScenarioCommand.getScenarioFile() == null) { // if no file uploaded LOGGER.debug("empty Scenario File"); errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY); return false; } Metadata metadata = new Metadata(); MimeTypes mimeTypes = TikaConfig.getDefaultConfig().getMimeRepository(); String mime; try { CommonsMultipartFile cmf = addScenarioCommand.getScenarioFile(); if (cmf.getSize() > maxFileSize) { Long maxFileSizeInMega = maxFileSize / 1000000; String[] arg = { maxFileSizeInMega.toString() }; errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, FILE_SIZE_EXCEEDED_MSG_BUNDLE_KEY, arg, "{0}"); return false; } else if (cmf.getSize() > 0) { mime = mimeTypes.detect(new BufferedInputStream(cmf.getInputStream()), metadata).toString(); LOGGER.debug("mime " + mime + " " + cmf.getOriginalFilename()); if (!authorizedMimeType.contains(mime)) { errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY); return false; } } else { LOGGER.debug("File with size null"); errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); errors.rejectValue(SCENARIO_FILE_KEY, NO_SCENARIO_UPLOADED_MSG_BUNDLE_KEY); return false; } } catch (IOException ex) { LOGGER.warn(ex); errors.rejectValue(SCENARIO_FILE_KEY, NOT_SCENARIO_MSG_BUNDLE_KEY); errors.rejectValue(GENERAL_ERROR_MSG_KEY, MANDATORY_FIELD_MSG_BUNDLE_KEY); return false; } return true; }
From source file:org.bibsonomy.webapp.controller.actions.JabRefImportController.java
/** * Writes the file of the specified layout part to disk and into the * database.//from w w w . j a va 2 s. c om * * @param loginUser * @param fileItem * @param layoutPart */ private void writeLayoutPart(final User loginUser, final CommonsMultipartFile fileItem, final LayoutPart layoutPart) { if (fileItem != null && fileItem.getSize() > 0) { log.debug("writing layout part " + layoutPart + " with file " + fileItem.getOriginalFilename()); try { final String hashedName = JabrefLayoutUtils.userLayoutHash(loginUser.getName(), layoutPart); final FileUploadInterface uploadFileHandler = this.uploadFactory.getFileUploadHandler( Collections.singletonList(fileItem.getFileItem()), FileUploadInterface.fileLayoutExt); /* * write file to disk */ final Document uploadedFile = uploadFileHandler.writeUploadedFile(hashedName, loginUser); /* * store row in database */ this.logic.createDocument(uploadedFile, null); } catch (Exception ex) { log.error("Could not add custom " + layoutPart + " layout." + ex.getMessage()); throw new RuntimeException("Could not add custom " + layoutPart + " layout: " + ex.getMessage()); } } }
From source file:org.jasig.ssp.service.impl.StudentDocumentServiceImpl.java
@Override public void createStudentDoc(UUID personId, StudentDocumentTO uploadItem, FileUploadResponse extjsFormResult) throws IOException, ObjectNotFoundException, ValidationException { CommonsMultipartFile file = uploadItem.getFile(); validateFile(file);/* w w w. j a va2s .c o m*/ String relativeFileLocation = calculateNewRelativeFileLocation(file.getOriginalFilename()); String absoluteFileLocation = calculateAbsoluteFileLocation(relativeFileLocation); File savedFile = new File(absoluteFileLocation); savedFile.mkdirs(); file.transferTo(savedFile); StudentDocument doc = createStudentDocFromUploadBean(uploadItem, relativeFileLocation, personId); save(doc); //set extjs return - sucsess extjsFormResult.setSuccess(true); }
From source file:org.jasig.ssp.service.impl.StudentDocumentServiceImpl.java
private synchronized void validateFile(CommonsMultipartFile file) { //validate file extension if (fileTypes == null) { initFileTypes();/*from w w w .ja v a 2 s .c om*/ } if (fileTypes.isEmpty()) { throw new IllegalArgumentException( "File upload is disabled because no accepted file types have been configured."); } String fname = file.getOriginalFilename().trim(); int extDelimIdx = fname.lastIndexOf("."); if (extDelimIdx < 0) { throw new IllegalArgumentException( "File type not accepted. Please try one of these types: " + fileTypes); } if (extDelimIdx == fname.length() - 1) { throw new IllegalArgumentException( "File type not accepted. Please try one of these types: " + fileTypes); } if (!(fileTypes.contains(fname.substring(extDelimIdx + 1)))) { throw new IllegalArgumentException( "File type not accepted. Please try one of these types: " + fileTypes); } }
From source file:org.springframework.web.multipart.commons.CommonsFileUploadSupport.java
/** * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, * containing Spring MultipartFile instances and a Map of multipart parameter. * @param fileItems the Commons FileIterms to parse * @param encoding the encoding to use for form fields * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) *//* w ww . ja va 2 s.c o m*/ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<>(); Map<String, String[]> multipartParameters = new HashMap<>(); Map<String, String> multipartParameterContentTypes = new HashMap<>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType()); } else { // multipart file field CommonsMultipartFile file = createMultipartFile(fileItem); multipartFiles.add(file.getName(), file); if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes); }