List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:org.apache.myfaces.custom.fileupload.UploadedFileDefaultFileImpl.java
public UploadedFileDefaultFileImpl(final FileItem fileItem) throws IOException { super(fileItem.getName(), fileItem.getContentType()); this.fileItem = (DiskFileItem) fileItem; storageStrategy = new DefaultDiskStorageStrategy(); }
From source file:org.apache.myfaces.custom.fileupload.UploadedFileDefaultMemoryImpl.java
public UploadedFileDefaultMemoryImpl(final FileItem fileItem) throws IOException { super(fileItem.getName(), fileItem.getContentType()); int sizeInBytes = (int) fileItem.getSize(); bytes = new byte[sizeInBytes]; this.fileItem = fileItem; fileItem.getInputStream().read(bytes); this.storageStrategy = new DefaultMemoryStorageStrategy(); }
From source file:org.apache.ofbiz.content.content.UploadContentAndImage.java
public static String uploadContentStuff(HttpServletRequest request, HttpServletResponse response) { try {/*from w w w . jav a 2 s . c o m*/ HttpSession session = request.getSession(); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); ServletFileUpload dfu = new ServletFileUpload( new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp"))); List<FileItem> lst = null; try { lst = UtilGenerics.checkList(dfu.parseRequest(request)); } catch (FileUploadException e4) { request.setAttribute("_ERROR_MESSAGE_", e4.getMessage()); Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module); return "error"; } if (lst.size() == 0) { request.setAttribute("_ERROR_MESSAGE_", "No files uploaded"); Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module); return "error"; } Map<String, Object> passedParams = new HashMap<String, Object>(); FileItem fi = null; FileItem imageFi = null; byte[] imageBytes = {}; passedParams.put("userLogin", userLogin); for (int i = 0; i < lst.size(); i++) { fi = lst.get(i); String fieldName = fi.getFieldName(); if (fi.isFormField()) { String fieldStr = fi.getString(); passedParams.put(fieldName, fieldStr); } else if (fieldName.startsWith("imageData")) { imageFi = fi; String fileName = fi.getName(); passedParams.put("drObjectInfo", fileName); String contentType = fi.getContentType(); passedParams.put("drMimeTypeId", contentType); imageBytes = imageFi.get(); passedParams.put(fieldName, imageBytes); if (Debug.infoOn()) { Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module); } } } if (Debug.infoOn()) { Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module); } // The number of multi form rows is retrieved int rowCount = UtilHttp.getMultiFormRowCount(request); if (rowCount < 1) { rowCount = 1; } TransactionUtil.begin(); for (int i = 0; i < rowCount; i++) { String suffix = "_o_" + i; if (i == 0) { suffix = ""; } String returnMsg = processContentUpload(passedParams, suffix, request); if (returnMsg.equals("error")) { try { TransactionUtil.rollback(); } catch (GenericTransactionException e2) { ServiceUtil.setMessages(request, e2.getMessage(), null, null); return "error"; } return "error"; } } TransactionUtil.commit(); } catch (Exception e) { Debug.logError(e, "[UploadContentAndImage] ", module); request.setAttribute("_ERROR_MESSAGE_", e.getMessage()); try { TransactionUtil.rollback(); } catch (GenericTransactionException e2) { request.setAttribute("_ERROR_MESSAGE_", e2.getMessage()); return "error"; } return "error"; } return "success"; }
From source file:org.apache.ofbiz.content.layout.LayoutWorker.java
/** * Uploads image data from a form and stores it in ImageDataResource. * Expects key data in a field identitified by the "idField" value * and the binary data to be in a field id'd by uploadField. *//* ww w . ja v a 2 s. c o m*/ public static Map<String, Object> uploadImageAndParameters(HttpServletRequest request, String uploadField) { Locale locale = UtilHttp.getLocale(request); Map<String, Object> results = new HashMap<String, Object>(); Map<String, String> formInput = new HashMap<String, String>(); results.put("formInput", formInput); ServletFileUpload fu = new ServletFileUpload( new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp"))); List<FileItem> lst = null; try { lst = UtilGenerics.checkList(fu.parseRequest(request)); } catch (FileUploadException e4) { return ServiceUtil.returnError(e4.getMessage()); } if (lst.size() == 0) { String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale); request.setAttribute("_ERROR_MESSAGE_", errMsg); return ServiceUtil .returnError(UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale)); } // This code finds the idField and the upload FileItems FileItem fi = null; FileItem imageFi = null; for (int i = 0; i < lst.size(); i++) { fi = lst.get(i); String fieldName = fi.getFieldName(); String fieldStr = fi.getString(); if (fi.isFormField()) { formInput.put(fieldName, fieldStr); request.setAttribute(fieldName, fieldStr); } if (fieldName.equals(uploadField)) { imageFi = fi; //MimeType of upload file results.put("uploadMimeType", fi.getContentType()); } } if (imageFi == null) { String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.image_null", UtilMisc.toMap("imageFi", imageFi), locale); request.setAttribute("_ERROR_MESSAGE_", errMsg); return null; } byte[] imageBytes = imageFi.get(); ByteBuffer byteWrap = ByteBuffer.wrap(imageBytes); results.put("imageData", byteWrap); results.put("imageFileName", imageFi.getName()); return results; }
From source file:org.apache.ofbiz.webapp.event.ServiceEventHandler.java
/** * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w . j av a2 s .com public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException { // make sure we have a valid reference to the Service Engine LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); if (dispatcher == null) { throw new EventHandlerException("The local service dispatcher is null"); } DispatchContext dctx = dispatcher.getDispatchContext(); if (dctx == null) { throw new EventHandlerException("Dispatch context cannot be found"); } // get the details for the service(s) to call String mode = SYNC; String serviceName = null; if (UtilValidate.isEmpty(event.path)) { mode = SYNC; } else { mode = event.path; } // make sure we have a defined service to call serviceName = event.invoke; if (serviceName == null) { throw new EventHandlerException("Service name (eventMethod) cannot be null"); } if (Debug.verboseOn()) Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module); // some needed info for when running the service Locale locale = UtilHttp.getLocale(request); TimeZone timeZone = UtilHttp.getTimeZone(request); HttpSession session = request.getSession(); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); // get the service model to generate context ModelService model = null; try { model = dctx.getModelService(serviceName); } catch (GenericServiceException e) { throw new EventHandlerException("Problems getting the service model", e); } if (model == null) { throw new EventHandlerException("Problems getting the service model"); } if (Debug.verboseOn()) { Debug.logVerbose("[Processing]: SERVICE Event", module); Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module); } boolean isMultiPart = ServletFileUpload.isMultipartContent(request); Map<String, Object> multiPartMap = new HashMap<String, Object>(); if (isMultiPart) { // get the http upload configuration String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1", dctx.getDelegator()); long maxUploadSize = -1; try { maxUploadSize = Long.parseLong(maxSizeStr); } catch (NumberFormatException e) { Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1", module); maxUploadSize = -1; } // get the http size threshold configuration - files bigger than this will be // temporarly stored on disk during upload String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.sizethreshold", "10240", dctx.getDelegator()); int sizeThreshold = 10240; // 10K try { sizeThreshold = Integer.parseInt(sizeThresholdStr); } catch (NumberFormatException e) { Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K", module); sizeThreshold = -1; } // directory used to temporarily store files that are larger than the configured size threshold String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general", "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator()); String encoding = request.getCharacterEncoding(); // check for multipart content types which may have uploaded items ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository))); // create the progress listener and add it to the session FileUploadProgressListener listener = new FileUploadProgressListener(); upload.setProgressListener(listener); session.setAttribute("uploadProgressListener", listener); if (encoding != null) { upload.setHeaderEncoding(encoding); } upload.setSizeMax(maxUploadSize); List<FileItem> uploadedItems = null; try { uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request)); } catch (FileUploadException e) { throw new EventHandlerException("Problems reading uploaded data", e); } if (uploadedItems != null) { for (FileItem item : uploadedItems) { String fieldName = item.getFieldName(); //byte[] itemBytes = item.get(); /* Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " + item.getContentType() + " FF: " + item.isFormField(), module); */ if (item.isFormField() || item.getName() == null) { if (multiPartMap.containsKey(fieldName)) { Object mapValue = multiPartMap.get(fieldName); if (mapValue instanceof List<?>) { checkList(mapValue, Object.class).add(item.getString()); } else if (mapValue instanceof String) { List<String> newList = new LinkedList<String>(); newList.add((String) mapValue); newList.add(item.getString()); multiPartMap.put(fieldName, newList); } else { Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module); } } else { if (encoding != null) { try { multiPartMap.put(fieldName, item.getString(encoding)); } catch (java.io.UnsupportedEncodingException uee) { Debug.logError(uee, "Unsupported Encoding, using deafault", module); multiPartMap.put(fieldName, item.getString()); } } else { multiPartMap.put(fieldName, item.getString()); } } } else { String fileName = item.getName(); if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) { // get just the file name IE and other browsers also pass in the local path int lastIndex = fileName.lastIndexOf('\\'); if (lastIndex == -1) { lastIndex = fileName.lastIndexOf('/'); } if (lastIndex > -1) { fileName = fileName.substring(lastIndex + 1); } } multiPartMap.put(fieldName, ByteBuffer.wrap(item.get())); multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize())); multiPartMap.put("_" + fieldName + "_fileName", fileName); multiPartMap.put("_" + fieldName + "_contentType", item.getContentType()); } } } } // store the multi-part map as an attribute so we can access the parameters request.setAttribute("multiPartMap", multiPartMap); Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request); Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet(); // we have a service and the model; build the context Map<String, Object> serviceContext = new HashMap<String, Object>(); for (ModelParam modelParam : model.getInModelParamList()) { String name = modelParam.name; // don't include userLogin, that's taken care of below if ("userLogin".equals(name)) continue; // don't include locale, that is also taken care of below if ("locale".equals(name)) continue; // don't include timeZone, that is also taken care of below if ("timeZone".equals(name)) continue; Object value = null; if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) { Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap, modelParam.stringMapPrefix, null); value = paramMap; if (Debug.verboseOn()) Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module); } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) { List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap, modelParam.stringListSuffix, null); value = paramList; } else { // first check the multi-part map value = multiPartMap.get(name); // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't if (UtilValidate.isEmpty(value)) { Object tempVal = request .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name : modelParam.requestAttributeName); if (tempVal != null) { value = tempVal; } } // check the request parameters if (UtilValidate.isEmpty(value)) { ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator()); // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up if ("any".equals(modelParam.allowHtml)) { value = request.getParameter(name); } else { // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc value = rawParametersMap.get(name); } // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes}) if (value == null) { value = UtilHttp.makeParamValueFromComposite(request, name, locale); } } // then session if (UtilValidate.isEmpty(value)) { Object tempVal = request.getSession() .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name : modelParam.sessionAttributeName); if (tempVal != null) { value = tempVal; } } // no field found if (value == null) { //still null, give up for this one continue; } if (value instanceof String && ((String) value).length() == 0) { // interpreting empty fields as null values for each in back end handling... value = null; } } // set even if null so that values will get nulled in the db later on serviceContext.put(name, value); } // get only the parameters for this service - converted to proper type // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any List<Object> errorMessages = new LinkedList<Object>(); serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone, locale); if (errorMessages.size() > 0) { // uh-oh, had some problems... request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages); return "error"; } // include the UserLogin value object if (userLogin != null) { serviceContext.put("userLogin", userLogin); } // include the Locale object if (locale != null) { serviceContext.put("locale", locale); } // include the TimeZone object if (timeZone != null) { serviceContext.put("timeZone", timeZone); } // invoke the service Map<String, Object> result = null; try { if (ASYNC.equalsIgnoreCase(mode)) { dispatcher.runAsync(serviceName, serviceContext); } else { result = dispatcher.runSync(serviceName, serviceContext); } } catch (ServiceAuthException e) { // not logging since the service engine already did request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage()); return "error"; } catch (ServiceValidationException e) { // not logging since the service engine already did request.setAttribute("serviceValidationException", e); if (e.getMessageList() != null) { request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList()); } else { request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage()); } return "error"; } catch (GenericServiceException e) { Debug.logError(e, "Service invocation error", module); throw new EventHandlerException("Service invocation error", e.getNested()); } String responseString = null; if (result == null) { responseString = ModelService.RESPOND_SUCCESS; } else { if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) { responseString = ModelService.RESPOND_SUCCESS; } else { responseString = (String) result.get(ModelService.RESPONSE_MESSAGE); } // set the messages in the request; this will be picked up by messages.ftl and displayed request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST)); request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP)); request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE)); request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST)); request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE)); // set the results in the request for (Map.Entry<String, Object> rme : result.entrySet()) { String resultKey = rme.getKey(); Object resultValue = rme.getValue(); if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) && !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) { request.setAttribute(resultKey, resultValue); } } } if (Debug.verboseOn()) Debug.logVerbose("[Event Return]: " + responseString, module); return responseString; }
From source file:org.apache.tapestry5.upload.internal.services.UploadedFileItemTest.java
@Test public void contentTypeIsFileItemContentType() throws Exception { FileItem item = newMock(FileItem.class); UploadedFileItem uploadedFile = new UploadedFileItem(item); expect(item.getContentType()).andReturn("foo"); replay();/*from w w w .j a v a 2s. c o m*/ assertEquals(uploadedFile.getContentType(), "foo"); verify(); }
From source file:org.appcelerator.transport.UploadTransportServlet.java
@Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getMethod().equalsIgnoreCase("POST")) { // paranoia check -we don't accept urlencoded transfers which are very bad performance wise if (false == ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "must be 'multipart/form-data'"); return; }//from ww w . ja v a2 s.c om String type = null; String callback = null; long size = 0L; // String instanceid = null; IMessageDataObject data = MessageUtils.createMessageDataObject(); try { ServletFileUpload upload = new ServletFileUpload(fileFactory); List items = upload.parseRequest(request); for (Iterator i = items.iterator(); i.hasNext();) { FileItem item = (FileItem) i.next(); if (item.isFormField()) { if (item.getFieldName().equals("callback")) { callback = item.getString(); continue; } else if (item.getFieldName().equals("type")) { type = item.getString(); continue; } else if (item.getFieldName().equals("instanceid")) { //instanceid = item.getString(); continue; } // place it in the data payload data.put(item.getFieldName(), item.getString()); } else { File f = null; if (tempDirectory != null) { f = File.createTempFile("sup", ".tmp", tempDirectory); } else { f = File.createTempFile("sup", ".tmp"); } f.deleteOnExit(); // write out the temporary file item.write(f); size = item.getSize(); IMessageDataObject filedata = MessageUtils.createMessageDataObject(); filedata.put("file", f.getAbsolutePath()); filedata.put("size", size); filedata.put("contentType", item.getContentType()); filedata.put("fieldName", item.getFieldName()); filedata.put("fileName", item.getName()); data.put("filedata", filedata); } } // required parameter type if (type == null || type.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing 'type' parameter"); return; } } catch (Throwable fe) { fe.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fe.getMessage()); return; } String scope = request.getParameter("scope"); String version = request.getParameter("version"); if (scope == null) { scope = "appcelerator"; } if (version == null) { version = "1.0"; } // create a message Message msg = new Message(); msg.setUser(request.getUserPrincipal()); msg.setSession(request.getSession()); msg.setServletRequest(request); msg.setType(type); msg.setData(data); msg.setAddress(InetAddress.getByName(request.getRemoteAddr())); msg.setScope(scope); msg.setVersion(version); // send the data ArrayList<Message> responses = new ArrayList<Message>(); try { ServiceRegistry.dispatch(msg, responses); } catch (Exception ex) { LOG.error("error dispatching upload message: " + msg, ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private"); response.setDateHeader("Expires", System.currentTimeMillis() - TimeUtil.ONE_YEAR); response.setContentType("text/html;charset=UTF-8"); // optionally, invoke a callback function/message on upload in the client if (callback != null || !responses.isEmpty()) { StringBuilder code = new StringBuilder(); code.append("<html><head><script>"); if (callback != null) { if (callback.startsWith("l:") || callback.startsWith("local:") || callback.startsWith("r:") || callback.startsWith("remote:")) { code.append(makeMessage(callback, "{size:" + size + "}", scope, version)); } else { // a javascript function to call code.append("window.parent.").append(callback).append("();"); } } for (Message m : responses) { code.append(makeMessage(m.getType(), m.getData().toDataString(), m.getScope(), m.getVersion())); } code.append("</script></head><body></body></html>"); // send the response response.setStatus(HttpServletResponse.SC_OK); response.getWriter().print(code.toString()); } else { response.setStatus(HttpServletResponse.SC_ACCEPTED); } } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "method was: " + request.getMethod()); } }
From source file:org.araneaframework.uilib.form.control.FileUploadControl.java
/** * Reads the {@link FileInfo}data from request using the {@link MultipartWrapper}. *///from w w w .ja va2 s . c o m protected void readFromRequest(String controlName, HttpServletRequest request) { OutputData output = (OutputData) request .getAttribute(StandardServletServiceAdapterComponent.OUTPUT_DATA_REQUEST_ATTRIBUTE); ServletFileUploadInputExtension fileUpload = (ServletFileUploadInputExtension) output .narrow(ServletFileUploadInputExtension.class); if (fileUpload.getUploadedFile(controlName) != null) { FileItem file = fileUpload.getUploadedFile(controlName); String mimeType = file.getContentType(); if (permittedMimeFileTypes == null || permittedMimeFileTypes.contains(mimeType)) { innerData = new FileInfo(file); } else { addError(ErrorUtil.localizeAndFormat(UiLibMessages.FORBIDDEN_MIME_TYPE, ErrorUtil.localize(getLabel(), getEnvironment()), getEnvironment())); } } }
From source file:org.axe.helper.mvc.FormRequestHelper.java
/** * /*from w w w.j a v a 2 s . c om*/ */ public static void initParam(Param param, HttpServletRequest request, String requestPath, String mappingPath) { List<FormParam> formParamList = new ArrayList<>(); List<FileParam> fileParamList = new ArrayList<>(); try { //???? Map<String, List<FileItem>> fileItemListMap = servletFileUpload.parseParameterMap(request); if (CollectionUtil.isNotEmpty(fileItemListMap)) { for (Map.Entry<String, List<FileItem>> fileItemListEntry : fileItemListMap.entrySet()) { String fieldName = fileItemListEntry.getKey(); List<FileItem> fileItemList = fileItemListEntry.getValue(); if (CollectionUtil.isNotEmpty(fileItemList)) { for (FileItem fileItem : fileItemList) { if (fileItem.isFormField()) { String fieldValue = fileItem.getString("UTF-8"); formParamList.add(new FormParam(fieldName, fieldValue)); } else { String fileName = FileUtil .getRealFileName(new String(fileItem.getName().getBytes(), "UTF-8")); if (StringUtil.isNotEmpty(fileName)) { long fileSize = fileItem.getSize(); String contentType = fileItem.getContentType(); InputStream inputStream = fileItem.getInputStream(); fileParamList.add( new FileParam(fieldName, fileName, fileSize, contentType, inputStream)); } } } } } } //?url? formParamList.addAll(RequestUtil.parseParameter(request, requestPath, mappingPath)); } catch (Exception e) { LOGGER.error("create param failed", e); throw new RuntimeException(e); } param.init(null, formParamList, fileParamList, null); }
From source file:org.castafiore.web.servlet.CastafioreServlet.java
/** * handles upload made by EXUpload component * @param request/* ww w . j av a2 s .c om*/ * @param response * @throws ServletException */ private void handleMultipartRequest(HttpServletRequest request, ServletResponse response) throws ServletException { //logger.debug("handling multipart request. A file is being uploaded...."); try { Map pro = BaseSpringUtil.getBean("uploadprops"); ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory(1024, new File(pro.get("repository.dir").toString()))); // set file upload progress listener FileUploadListener listener = new FileUploadListener(); HttpSession session = request.getSession(); session.setAttribute("LISTENER", listener); // upload servlet allows to set upload listener upload.setProgressListener(listener); Iterator iter = upload.parseRequest(request).iterator(); //FileItemIterator iter = upload.getItemIterator(request); String applicationId = null; String componentId = null; EXUpload exUpload = null; Application applicationInstance = null; List<FileData> ds = new ArrayList<FileData>(); //String name = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { if (item.getFieldName().equals("casta_applicationid")) { applicationId = IOUtil.getStreamContentAsString(item.getInputStream()); //logger.debug("applicationid for upload:" + applicationId); applicationInstance = (Application) request.getSession().getAttribute(applicationId); } else if (item.getFieldName().equalsIgnoreCase("casta_componentid")) { componentId = IOUtil.getStreamContentAsString(item.getInputStream()); //logger.debug("componentid for upload:" + componentId); } } else { FileData bFile = null; System.out.println(item.getName()); String name = item.getName(); //logger.debug("opening client stream..."); File savedFile = new File( pro.get("upload.dir") + "/" + new Date().getTime() + "_" + item.getName()); //new File(request.getRealPath("/")+"uploadedFiles/"+name); item.write(savedFile); String contentType = item.getContentType(); //logger.debug("content type of file:" + contentType); bFile = getNewInstance(); bFile.setUrl(savedFile.getAbsolutePath()); bFile.setName(item.getName()); bFile.setName(name); ds.add(bFile); //exUpload.addFile(bFile); } } exUpload = (EXUpload) applicationInstance.getDescendentById(componentId); for (FileData f : ds) { exUpload.addFile(f); } //logger.debug("upload is complete. The binary file can be obtained using EXFileUpload.getFile()"); } catch (Exception e) { throw new ServletException(e); } }