List of usage examples for org.apache.commons.fileupload FileItem getContentType
String getContentType();
null
if not defined. From source file:org.exoplatform.wiki.service.impl.WikiRestServiceImpl.java
@POST @Path("/upload/{wikiType}/{wikiOwner:.+}/{pageId}/") public Response upload(@PathParam("wikiType") String wikiType, @PathParam("wikiOwner") String wikiOwner, @PathParam("pageId") String pageId) { EnvironmentContext env = EnvironmentContext.getCurrent(); HttpServletRequest req = (HttpServletRequest) env.get(HttpServletRequest.class); boolean isMultipart = FileUploadBase.isMultipartContent(req); if (isMultipart) { DiskFileUpload upload = new DiskFileUpload(); // Parse the request try {// w w w .j av a 2s.c o m List<FileItem> items = upload.parseRequest(req); for (FileItem fileItem : items) { InputStream inputStream = fileItem.getInputStream(); byte[] imageBytes; if (inputStream != null) { imageBytes = new byte[inputStream.available()]; inputStream.read(imageBytes); } else { imageBytes = null; } String fileName = fileItem.getName(); String fileType = fileItem.getContentType(); if (fileName != null) { // It's necessary because IE posts full path of uploaded files fileName = FilenameUtils.getName(fileName); fileType = FilenameUtils.getExtension(fileName); } String mimeType = new MimeTypeResolver().getMimeType(fileName); WikiResource attachfile = new WikiResource(mimeType, "UTF-8", imageBytes); attachfile.setName(fileName); if (attachfile != null) { WikiService wikiService = (WikiService) PortalContainer.getComponent(WikiService.class); Page page = wikiService.getExsitedOrNewDraftPageById(wikiType, wikiOwner, pageId); if (page != null) { AttachmentImpl att = ((PageImpl) page).createAttachment(attachfile.getName(), attachfile); ConversationState conversationState = ConversationState.getCurrent(); String creator = null; if (conversationState != null && conversationState.getIdentity() != null) { creator = conversationState.getIdentity().getUserId(); } att.setCreator(creator); Utils.reparePermissions(att); } } } } catch (Exception e) { log.error(e.getMessage(), e); return Response.status(HTTPStatus.BAD_REQUEST).entity(e.getMessage()).build(); } } return Response.ok().build(); }
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
private void mapRequestToObj(HashMap<String, Object> data, Class expectedClass, Object obj) throws Exception { if (obj == null) { throw new ApplicationException("mapRequestToObj called on NULL obj", "ERR9001"); }//from w w w.j a va 2s .c o m try { Method versionMethod = expectedClass.getMethod("getVersion", (Class<?>[]) null); Long objVersion = (Long) versionMethod.invoke(obj, (Object[]) null); String clientVersion = (String) data.get("version"); if (objVersion != null && clientVersion != null) { try { long clientVersionLong = Long.parseLong(clientVersion); if (!objVersion.equals(clientVersionLong)) { throw makeApplicationException("Can't save object", "ERR9016", (Serializable[]) null); } } catch (NumberFormatException nfe) { // Version from client isn't number - ignore } } } catch (NoSuchMethodException nme) { // No version control } Method[] methods = expectedClass.getMethods(); for (Method m : methods) { Class<?>[] paramTypes = m.getParameterTypes(); Class persistentClass = null; if (paramTypes.length == 1) { if (paramTypes[0].getAnnotation(Entity.class) != null) { persistentClass = paramTypes[0]; } else if (paramTypes[0].getAnnotation(Embeddable.class) != null) { persistentClass = paramTypes[0]; } } ServiceDescription srvParam = paramTypes.length == 1 ? findServiceByClassName(paramTypes[0].getName()) : null; if ((m.getName().startsWith(SET_PREFIX) && paramTypes.length == 1 && (paramTypes[0].isAssignableFrom(String.class) || paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE) || paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE) || paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE) || paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE) || paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE) || paramTypes[0].equals(Date.class) || Enum.class.isAssignableFrom(paramTypes[0]) || (srvParam != null && srvParam.getFindById() != null) || persistentClass != null)) || (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType())))) { String fldName; if (m.getName().startsWith(GET_TRANSLATE)) { fldName = m.getName().substring(GET_TRANSLATE_LENGTH, GET_TRANSLATE_LENGTH + 1).toLowerCase() + m.getName().substring(GET_TRANSLATE_LENGTH + 1); } else { fldName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); } Object value = data.get(fldName); if (value == null) { fldName = m.getName().substring(3); value = data.get(fldName); } if (value != null) { Object typedVal; String val = null; if (value instanceof String) { val = (String) value; } log.log(Level.FINER, " value = " + value); if (m.getName().startsWith(GET_PREFIX) && paramTypes.length == 0 && (Set.class.isAssignableFrom(m.getReturnType()) || List.class.isAssignableFrom(m.getReturnType()))) { log.log(Level.FINER, "GET"); String attrName = m.getName().substring(3, 4).toLowerCase() + m.getName().substring(4); Type[] actualTypeArguments = null; Class iterClass = expectedClass; while (iterClass != null) { try { Field field = iterClass.getDeclaredField(attrName); ParameterizedType genericType = (ParameterizedType) field.getGenericType(); actualTypeArguments = genericType.getActualTypeArguments(); break; } catch (NoSuchFieldException nsfe) { // do nothing iterate again } iterClass = iterClass.getSuperclass(); iterClass = iterClass.equals(Object.class) ? null : iterClass; } if (actualTypeArguments != null && actualTypeArguments.length == 1 && actualTypeArguments[0] instanceof Class) { Class assocClass = (Class) actualTypeArguments[0]; ServiceDescription assocService = findServiceByClassName(assocClass.getName()); Collection dbValueSet = (Collection) m.invoke(obj, (Object[]) null); if (value == null || !(value instanceof HashMap)) { log.log(Level.FINE, "No data for db property {0}", attrName); } else if (assocService != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { boolean wasMatchingGuiVal = false; ArrayList<String> removeKeys = new ArrayList<String>(); for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object guiValue = ((HashMap<String, Object>) object).get("id"); if (guiValue.equals(dbValId)) { removeKeys.add(key); wasMatchingGuiVal = true; mapRequestToObj((HashMap<String, Object>) guiValue, assocClass, dbVal); break; } } else if (object instanceof String) { // Association if (dbValId.equals(object)) { removeKeys.add(key); wasMatchingGuiVal = true; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } // Remove processed elements // Direct remove is firing concurrent modification exception for (String removeKey : removeKeys) { guiValueMap.remove(removeKey); } if (!wasMatchingGuiVal) { // Is not in list comming from GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else if (object instanceof String) { // Association try { Long id = new Long((String) object); Object assocObj = assocService.getFindById().invoke( assocService.getInstance(), ServiceContextStore.get(), id); if (assocObj != null) { dbValueSet.add(assocObj); } else { log.log(Level.WARNING, "Object with ID {0} not availabla via service {1}", new Object[] { id, assocService.getName() }); } } catch (Exception ex) { log.log(Level.WARNING, "No ID parsable from value {0} under key {1}", new Object[] { object, key }); } } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } else if (assocClass != null) { HashMap<String, Object> guiValueMap = (HashMap<String, Object>) value; ArrayList<Object> removeIt = new ArrayList<Object>(); Iterator dbIterator = dbValueSet.iterator(); while (dbIterator.hasNext()) { Object dbVal = dbIterator.next(); String dbValId = getIdFromObj(dbVal); if (dbValId != null) { Object matchingGuiVal = null; for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { HashMap<String, Object> guiVal = (HashMap<String, Object>) object; if (dbValId.equals(guiVal.get("id"))) { guiValueMap.remove(key); matchingGuiVal = guiVal; break; } } else { log.log(Level.WARNING, "Wrong object type from GUI under key {0}", key); } } if (matchingGuiVal != null) { // Coming from GUI - update mapRequestToObj((HashMap<String, Object>) matchingGuiVal, assocClass, dbVal); } else { // Not in GUI - delete removeIt.add(dbVal); } } else { log.log(Level.WARNING, "No ID in object {0}", dbVal); } } dbValueSet.removeAll(removeIt); // Rest are new records for (String key : guiValueMap.keySet()) { Object object = guiValueMap.get(key); if (object instanceof HashMap) { Object subObj = makeNewInstance(assocClass, (HashMap<String, Object>) object); mapRequestToObj((HashMap<String, Object>) object, assocClass, subObj); dbValueSet.add(subObj); } else { log.log(Level.WARNING, "Wrong sub type {0}", attrName); } } } } else { log.log(Level.WARNING, "No DB mapping or not of collection type: {0}", attrName); } typedVal = null; } else if (paramTypes[0].isAssignableFrom(String.class)) { typedVal = val; } else if (paramTypes[0].equals(Integer.class) || paramTypes[0].equals(Integer.TYPE)) { typedVal = Integer.parseInt(val); } else if (paramTypes[0].equals(Long.class) || paramTypes[0].equals(Long.TYPE)) { typedVal = Long.parseLong(val); } else if (paramTypes[0].equals(Double.class) || paramTypes[0].equals(Double.TYPE)) { typedVal = Double.parseDouble(val); } else if (paramTypes[0].equals(Float.class) || paramTypes[0].equals(Float.TYPE)) { typedVal = Float.parseFloat(val); } else if (paramTypes[0].equals(Boolean.class) || paramTypes[0].equals(Boolean.TYPE)) { typedVal = "true".equalsIgnoreCase(val) || "t".equalsIgnoreCase(val) || "y".equalsIgnoreCase(val); } else if (paramTypes[0].isAssignableFrom(Date.class)) { typedVal = dateFormat.parse(val); } else if (Enum.class.isAssignableFrom(paramTypes[0])) { try { Method fromValueMethod = paramTypes[0].getMethod("fromValue", String.class); typedVal = fromValueMethod.invoke(null, val); } catch (Exception ex) { typedVal = null; } try { if (typedVal == null) { Method valueOfMethod = paramTypes[0].getMethod("valueOf", String.class); typedVal = valueOfMethod.invoke(null, val); } } catch (Exception ex) { typedVal = null; } } else if (persistentClass != null && persistentClass.equals(FileUpload.class)) { FileItem fileItem = uploadServlet.getFileItem(sessionId.get(), fldName, val); if (fileItem != null) { typedVal = fileUploadService.uploadFile(ServiceContextStore.get(), fileItem.getName(), fileItem.getContentType(), fileItem.getInputStream()); } else { typedVal = null; } } else if (srvParam != null && srvParam.getFindById() != null) { if (value instanceof HashMap) { HashMap<String, Object> embeddedObj = (HashMap<String, Object>) value; typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), new Long((String) embeddedObj.get("id"))); mapRequestToObj(embeddedObj, srvParam.getExpectedClass(), typedVal); } else { try { Long parsedId = new Long(val); typedVal = srvParam.getFindById().invoke(srvParam.getInstance(), ServiceContextStore.get(), parsedId); } catch (NumberFormatException nfe) { // wrong value typedVal = null; } } } else if (persistentClass != null) { String getMethodName = "g" + m.getName().substring(1); try { Method getMethod = obj.getClass().getMethod(getMethodName, (Class[]) null); typedVal = getMethod.invoke(obj, (Object[]) null); } catch (NoSuchMethodException nsme) { typedVal = null; } if (typedVal == null) { typedVal = makeNewInstance(persistentClass, (HashMap<String, Object>) value); } mapRequestToObj((HashMap<String, Object>) value, typedVal.getClass(), typedVal); } else { log.log(Level.WARNING, "Can't convert value for: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); typedVal = null; } if (typedVal != null) { m.invoke(obj, typedVal); } } } else if (m.getName().startsWith(SET_PREFIX)) { log.log(Level.WARNING, "Unusable setter method: {0}.{1} ({2})", new Object[] { expectedClass.getName(), m.getName(), (paramTypes.length == 1 ? paramTypes[0].getName() : paramTypes.toString()) }); } } }
From source file:org.gatein.management.gadget.mop.exportimport.server.FileUploadServlet.java
/** * Override executeAction to save the received files in a custom place and delete this items from session. *//* w w w .j a v a2 s . co m*/ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { StringBuilder response = new StringBuilder("<response>\n"); int count = 0; for (FileItem item : sessionFiles) { // if (false == item.isFormField()) { if (!item.isFormField()) { count++; try { // Create a new file based on the remote file name in the client String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_"); // Create a temporary file placed in the default system temp folder File file = File.createTempFile(saveName, ".zip"); item.write(file); // Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); String importMode = request.getParameter("importMode"); // process the uploaded file processImport(request.getParameter("pc"), new FileInputStream(file), importMode); // Compose a xml message with the full file information which can be parsed in client side response.append("<file-").append(count).append("-field>").append(item.getFieldName()) .append("</file-").append(count).append("-field>\n"); response.append("<file-").append(count).append("-name>").append(item.getName()) .append("</file-").append(count).append("-name>\n"); response.append("<file-").append(count).append("-size>").append(item.getSize()) .append("</file-").append(count).append("-size>\n"); response.append("<file-").append(count).append("-type>").append(item.getContentType()) .append("</file-").append(count).append("type>\n"); } catch (Exception e) { throw new UploadActionException(e); } } } // Remove files from session because we have a copy of them removeSessionFileItems(request); // Send information of the received files to the client. return response.append("</response>\n").toString(); }
From source file:org.gatein.management.gadget.server.FileUploadServlet.java
/** * Override executeAction to save the received files in a custom place * and delete this items from session.//from w w w . java 2 s .com */ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { StringBuilder response = new StringBuilder("<response>\n"); int count = 0; for (FileItem item : sessionFiles) { //if (false == item.isFormField()) { if (!item.isFormField()) { count++; try { // Create a new file based on the remote file name in the client String saveName = item.getName().replaceAll("[\\\\/><\\|\\s\"'{}()\\[\\]]+", "_"); // Create a temporary file placed in the default system temp folder File file = File.createTempFile(saveName, ".zip"); item.write(file); // Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); String overwriteVal = request.getParameter("overwrite"); boolean overwrite = Boolean.parseBoolean(overwriteVal); // process the uploaded file processImport(request.getParameter("pc"), new FileInputStream(file), overwrite); // Compose a xml message with the full file information which can be parsed in client side response.append("<file-").append(count).append("-field>").append(item.getFieldName()) .append("</file-").append(count).append("-field>\n"); response.append("<file-").append(count).append("-name>").append(item.getName()) .append("</file-").append(count).append("-name>\n"); response.append("<file-").append(count).append("-size>").append(item.getSize()) .append("</file-").append(count).append("-size>\n"); response.append("<file-").append(count).append("-type>").append(item.getContentType()) .append("</file-").append(count).append("type>\n"); } catch (Exception e) { throw new UploadActionException(e); } } } // Remove files from session because we have a copy of them removeSessionFileItems(request); // Send information of the received files to the client. return response.append("</response>\n").toString(); }
From source file:org.gatein.wcm.portlet.editor.views.ManagerActions.java
public String actionNewImport(ActionRequest request, ActionResponse response, UserWcm userWcm) { log.info("WCM Import: STARTED"); String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR); FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir)); PortletFileUpload importUpload = new PortletFileUpload(factory); try {// w w w . j ava2s . c o m List<FileItem> items = importUpload.parseRequest(request); FileItem file = null; String importStrategy = String.valueOf(Wcm.IMPORT.STRATEGY.NEW); for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { importStrategy = item.getString(); } } // .zip validation if (file != null && file.getContentType() != null && !"application/zip".equalsIgnoreCase(file.getContentType())) { throw new WcmException("File: " + file.getName() + " is not application/zip."); } // log.info("Importing ... " + file.getName() + " with strategy " + importStrategy); wcm.importRepository(file.getInputStream(), importStrategy.charAt(0), userWcm); } catch (Exception e) { log.warning("Error importing file"); e.printStackTrace(); response.setRenderParameter("errorWcm", "Error importing file: " + e.toString()); } log.info("WCM Import: FINISHED"); return Wcm.VIEWS.MANAGER; }
From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java
public String actionNewUpload(ActionRequest request, ActionResponse response, UserWcm userWcm) { String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR); FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir)); PortletFileUpload upload = new PortletFileUpload(factory); try {/*from www. j a v a2s . c om*/ List<FileItem> items = upload.parseRequest(request); FileItem file = null; String description = ""; for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { description = item.getString(); } } Upload newUpload = new Upload(); newUpload.setFileName(file.getName()); newUpload.setMimeType(file.getContentType()); newUpload.setDescription(description); wcm.create(newUpload, file.getInputStream(), userWcm); return Wcm.VIEWS.UPLOADS; } catch (Exception e) { log.warning("Error uploading file"); e.printStackTrace(); response.setRenderParameter("errorWcm", "Error uploading file " + e.toString()); } return Wcm.VIEWS.UPLOADS; }
From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java
public String actionEditUpload(ActionRequest request, ActionResponse response, UserWcm userWcm) { String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR); FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir)); PortletFileUpload upload = new PortletFileUpload(factory); try {/*from ww w . j ava 2 s .c o m*/ List<FileItem> items = upload.parseRequest(request); FileItem file = null; String description = null; String editUploadId = null; for (FileItem item : items) { if (!item.isFormField()) { file = item; } else { if (item.getFieldName().equals("uploadFileDescription")) { description = item.getString(); } else if (item.getFieldName().equals("editUploadId")) { editUploadId = item.getString(); } } } Upload updateUpload = wcm.findUpload(new Long(editUploadId), userWcm); if (updateUpload != null) { if (file != null && file.getSize() > 0 && file.getName().length() > 0) { updateUpload.setFileName(file.getName()); updateUpload.setMimeType(file.getContentType()); updateUpload.setDescription(description); wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm); wcm.update(updateUpload, file.getInputStream(), userWcm); } else { if (description != null) { updateUpload.setDescription(description); wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm); wcm.update(updateUpload, userWcm); } } } return Wcm.VIEWS.UPLOADS; } catch (Exception e) { log.warning("Error uploading file"); e.printStackTrace(); response.setRenderParameter("errorWcm", "Error uploading file " + e.toString()); } return Wcm.VIEWS.UPLOADS; }
From source file:org.getobjects.appserver.elements.WOFileUpload.java
@Override public void takeValuesFromRequest(final WORequest _rq, final WOContext _ctx) { final Object cursor = _ctx.cursor(); String formName = this.elementNameInContext(_ctx); Object formValue = _rq.formValueForKey(formName); if (this.writeValue != null) this.writeValue.setValue(formValue, cursor); if (formValue == null) { if (this.filePath != null) this.filePath.setValue(null, cursor); if (this.data != null) this.data.setValue(null, cursor); } else if (formValue instanceof String) { /* this happens if the enctype is not multipart/formdata */ if (this.filePath != null) this.filePath.setStringValue((String) formValue, cursor); } else if (formValue instanceof FileItem) { FileItem fileItem = (FileItem) formValue; if (this.size != null) this.size.setValue(fileItem.getSize(), cursor); if (this.contentType != null) this.contentType.setStringValue(fileItem.getContentType(), cursor); if (this.filePath != null) this.filePath.setStringValue(fileItem.getName(), cursor); /* process content */ if (this.data != null) this.data.setValue(fileItem.get(), cursor); else if (this.string != null) { // TODO: we could support a encoding get-binding this.string.setStringValue(fileItem.getString(), cursor); } else if (this.inputStream != null) { try { this.inputStream.setValue(fileItem.getInputStream(), cursor); } catch (IOException e) { log.error("failed to get input stream for upload file", e); this.inputStream.setValue(null, cursor); }//from w ww. ja va 2 s .co m } /* delete temporary file */ if (this.deleteAfterPush != null) { if (this.deleteAfterPush.booleanValueInComponent(cursor)) fileItem.delete(); } } else log.warn("cannot process WOFileUpload value: " + formValue); }
From source file:org.gluewine.rest_server.RESTServlet.java
/** * Parses the parameters from the form stored in the given map. * * @param rm The method to process./*from w ww . j a v a 2 s . com*/ * @param formFields The fields to parse. * @param serializer The serializer to use. * @param params the parameter value array to fill in. * @param paramTypes the parameter types array. * @throws IOException If an error occurs. */ private void fillParamValuesFromForm(RESTMethod rm, Map<String, FileItem> formFields, RESTSerializer serializer, Object[] params, Class<?>[] paramTypes) throws IOException { for (int i = 0; i < params.length; i++) { if (params[i] != null) continue; RESTID id = AnnotationUtility.getAnnotations(RESTID.class, rm.getObject(), rm.getMethod(), i); if (id != null) { FileItem item = formFields.get(id.id()); if (item != null) { String[] val = null; if (item.isFormField()) { val = new String[] { item.getString("UTF-8") }; params[i] = serializer.deserialize(paramTypes[i], val); if (logger.isTraceEnabled()) traceParameter(id.id(), val); } else { if (id.mimetype()) { params[i] = item.getContentType(); } else if (id.filename()) { params[i] = item.getName(); } else { try { if (InputStream.class.isAssignableFrom(paramTypes[i])) { params[i] = item.getInputStream(); } else { File nf = new File(item.getName()); File f = File.createTempFile("___", "___" + nf.getName()); item.write(f); if (File.class.isAssignableFrom(paramTypes[i])) { params[i] = f; } else { logger.warn("File upload to string field for method " + rm.getMethod()); params[i] = f.getAbsolutePath(); } } } catch (Exception e) { throw new IOException(e.getMessage()); } } } } } } }
From source file:org.infoglue.deliver.taglib.common.ParseMultipartTag.java
/** * Process the end tag. Sets a cookie. * /*from w w w. j a v a 2 s .c om*/ * @return indication of whether to continue evaluating the JSP page. * @throws JspException if an error occurred while processing this tag. */ public int doEndTag() throws JspException { Map parameters = new HashMap(); try { //Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); //Set factory constraints factory.setSizeThreshold(maxSize.intValue()); //factory.setRepository(new File(CmsPropertyHandler.getDigitalAssetPath())); //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); //Set overall request size constraint upload.setSizeMax(this.maxSize.intValue()); if (upload.isMultipartContent(this.getController().getHttpServletRequest())) { //Parse the request List items = upload.parseRequest(this.getController().getHttpServletRequest()); List files = new ArrayList(); //Process the uploaded items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); if (isValidContentType(contentType)) { files.add(item); } else { if ((item.getName() == null || item.getName().equals("")) && this.ignoreEmpty) { logger.warn("Empty file but that was ok.."); } else { pageContext.setAttribute("status", "nok"); pageContext.setAttribute("upload_error", "A field did not have a valid content type"); pageContext.setAttribute(fieldName + "_error", "Not a valid content type"); //throw new JspException("Not a valid content type"); } } } else { String name = item.getFieldName(); String value = item.getString(); String oldValue = (String) parameters.get(name); if (oldValue != null) value = oldValue + "," + value; if (value != null) { try { String fromEncoding = "iso-8859-1"; String toEncoding = "utf-8"; String testValue = new String(value.getBytes(fromEncoding), toEncoding); if (testValue.indexOf((char) 65533) == -1) value = testValue; } catch (Exception e) { e.printStackTrace(); } } parameters.put(name, value); } } parameters.put("files", files); setResultAttribute(parameters); } else { setResultAttribute(null); } } catch (Exception e) { logger.warn("Error doing an upload" + e.getMessage(), e); //pageContext.setAttribute("fieldName_exception", "contentType_MAX"); //throw new JspException("File upload failed: " + e.getMessage()); pageContext.setAttribute("status", "nok"); pageContext.setAttribute("upload_error", "" + e.getMessage()); } return EVAL_PAGE; }