protected void encodeChooseButton(FacesContext context, FileUpload fileUpload, boolean disabled) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = fileUpload.getClientId(context); String cssClass = HTML.BUTTON_TEXT_ICON_LEFT_BUTTON_CLASS + " " + FileUpload.CHOOSE_BUTTON_CLASS; if (disabled) { cssClass += " ui-state-disabled"; } writer.startElement("span", null); writer.writeAttribute("class", cssClass, null); // button icon writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_LEFT_ICON_CLASS + " ui-icon-plusthick", null); writer.endElement("span"); // text writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_TEXT_CLASS, null); writer.writeText(fileUpload.getLabel(), "value"); writer.endElement("span"); if (!disabled) { encodeInputField(context, fileUpload, clientId + "_input"); } writer.endElement("span"); }
public String getSimpleInputDecodeId(FileUpload fileUpload, FacesContext context) { String clientId = fileUpload.getClientId(context); if (fileUpload.getMode().equals("simple") && !fileUpload.isSkinSimple()) { return clientId; } else { return clientId + "_input"; } }
@Override public void decode(FacesContext context, UIComponent component) { FileUpload fileUpload = (FileUpload) component; if (!fileUpload.isDisabled()) { if (RequestContext.getCurrentInstance().getApplicationContext().getConfig().isAtLeastJSF22()) NativeFileUploadDecoder.decode(context, fileUpload); else CommonsFileUploadDecoder.decode(context, fileUpload); } }
@Override public Object getConvertedValue( FacesContext context, UIComponent component, Object submittedValue) throws ConverterException { FileUpload fileUpload = (FileUpload) component; if (fileUpload.getMode().equals("simple") && submittedValue != null && submittedValue.equals("")) { return null; } else { return submittedValue; } }
protected void encodeMarkup(FacesContext context, FileUpload fileUpload) throws IOException { if (fileUpload.getMode().equals("simple")) { encodeSimpleMarkup(context, fileUpload); } else { encodeAdvancedMarkup(context, fileUpload); } }
/** * Creates a new bucket for the current HTTP session and returns it's id. * * @param maxCount Maximum number of files that may be uploaded into the bucket, or -1 for no * restriction. * @param maxSize Maximum size of a file that may be uploaded into the bucket in kilobytes, or -1 * for no restriction. * @param allowedFormats space separated list of file name extensions, or empty string for no * restriction. * @param thumbnailSize maximum size of server-side generated image thumbnails. It might be width * or height dependent on image orientation. * @param minSeq initial item sequence number (typically 1) * @return new bucket id. */ public String newBucket( int maxCount, int maxSize, String allowedFormats, int thumbnailSize, int minSeq) { return fileUpload .createBucket( new UploadBucketConfig(maxCount, maxSize, allowedFormats, thumbnailSize), minSeq) .getId(); }
public int compareTo(FileUpload o) { int v; v = getName().compareToIgnoreCase(o.getName()); if (v != 0) { return v; } // TODO should we compare size ? return v; }
protected void encodeInputField(FacesContext context, FileUpload fileUpload, String clientId) throws IOException { ResponseWriter writer = context.getResponseWriter(); String inputId = clientId + "_input"; writer.startElement("input", null); writer.writeAttribute("type", "file", null); writer.writeAttribute("id", inputId, null); writer.writeAttribute("name", inputId, null); if (fileUpload.isMultiple()) writer.writeAttribute("multiple", "multiple", null); if (fileUpload.isDisabled()) writer.writeAttribute("disabled", "disabled", "disabled"); if (fileUpload.getAccept() != null) writer.writeAttribute("accept", fileUpload.getAccept(), null); renderDynamicPassThruAttributes(context, fileUpload); writer.writeAttribute("aria-labelledby", clientId + "_label", null); writer.endElement("input"); }
protected void encodeSimpleInputField( FacesContext context, FileUpload fileUpload, String clientId, String style, String styleClass) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("input", null); writer.writeAttribute("type", "file", null); writer.writeAttribute("id", clientId, null); writer.writeAttribute("name", clientId, null); if (fileUpload.isMultiple()) writer.writeAttribute("multiple", "multiple", null); if (fileUpload.isDisabled()) writer.writeAttribute("disabled", "disabled", "disabled"); if (fileUpload.getAccept() != null) writer.writeAttribute("accept", fileUpload.getAccept(), null); if (style != null) writer.writeAttribute("style", style, "style"); if (styleClass != null) writer.writeAttribute("class", styleClass, "styleClass"); renderDynamicPassThruAttributes(context, fileUpload); writer.endElement("input"); }
protected void encodeAdvancedMarkup(FacesContext context, FileUpload fileUpload) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = fileUpload.getClientId(context); String style = fileUpload.getStyle(); String styleClass = fileUpload.getStyleClass(); styleClass = styleClass == null ? FileUpload.CONTAINER_CLASS : FileUpload.CONTAINER_CLASS + " " + styleClass; boolean disabled = fileUpload.isDisabled(); writer.startElement("div", fileUpload); writer.writeAttribute("id", clientId, "id"); writer.writeAttribute("class", styleClass, styleClass); if (style != null) { writer.writeAttribute("style", style, "style"); } // buttonbar writer.startElement("div", fileUpload); writer.writeAttribute("class", FileUpload.BUTTON_BAR_CLASS, null); // choose button encodeChooseButton(context, fileUpload, disabled); if (!fileUpload.isAuto()) { encodeButton( context, fileUpload.getUploadLabel(), FileUpload.UPLOAD_BUTTON_CLASS, "ui-icon-arrowreturnthick-1-n"); encodeButton( context, fileUpload.getCancelLabel(), FileUpload.CANCEL_BUTTON_CLASS, "ui-icon-cancel"); } writer.endElement("div"); renderChildren(context, fileUpload); // content writer.startElement("div", null); writer.writeAttribute("class", FileUpload.CONTENT_CLASS, null); writer.startElement("table", null); writer.writeAttribute("class", FileUpload.FILES_CLASS, null); writer.startElement("tbody", null); writer.endElement("tbody"); writer.endElement("table"); writer.endElement("div"); writer.endElement("div"); }
@Override public void decode(FacesContext context, UIComponent component) { if (!context .getExternalContext() .getRequestContentType() .toLowerCase() .startsWith("multipart/")) { return; } FileUpload fileUpload = (FileUpload) component; if (!fileUpload.isDisabled()) { PrimeConfiguration cc = RequestContext.getCurrentInstance().getApplicationContext().getConfig(); String uploader = cc.getUploader(); boolean isAtLeastJSF22 = cc.isAtLeastJSF22(); String inputToDecodeId = getSimpleInputDecodeId(fileUpload, context); if (uploader.equals("auto")) { if (isAtLeastJSF22) { NativeFileUploadDecoder.decode(context, fileUpload, inputToDecodeId); } else { CommonsFileUploadDecoder.decode(context, fileUpload, inputToDecodeId); } } else if (uploader.equals("native")) { if (!isAtLeastJSF22) { throw new FacesException("native uploader requires at least a JSF 2.2 runtime"); } NativeFileUploadDecoder.decode(context, fileUpload, inputToDecodeId); } else if (uploader.equals("commons")) { CommonsFileUploadDecoder.decode(context, fileUpload, inputToDecodeId); } } }
/** * Add a file as a FileUpload * * @param name the name of the parameter * @param file the file to be uploaded (if not Multipart mode, only the filename will be included) * @param contentType the associated contentType for the File * @param isText True if this file should be transmitted in Text format (else binary) * @throws NullPointerException for name and file * @throws ErrorDataEncoderException if the encoding is in error or if the finalize were already * done */ public void addBodyFileUpload(String name, File file, String contentType, boolean isText) throws ErrorDataEncoderException { if (name == null) { throw new NullPointerException("name"); } if (file == null) { throw new NullPointerException("file"); } String scontentType = contentType; String contentTransferEncoding = null; if (contentType == null) { if (isText) { scontentType = HttpPostBodyUtil.DEFAULT_TEXT_CONTENT_TYPE; } else { scontentType = HttpPostBodyUtil.DEFAULT_BINARY_CONTENT_TYPE; } } if (!isText) { contentTransferEncoding = HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value; } FileUpload fileUpload = factory.createFileUpload( request, name, file.getName(), scontentType, contentTransferEncoding, null, file.length()); try { fileUpload.setContent(file); } catch (IOException e) { throw new ErrorDataEncoderException(e); } addBodyHttpData(fileUpload); }
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { httpRequestContext.set(new HttpRequestContext(this, req, resp)); try { String ctype = req.getContentType(); if (ctype != null) ctype = ctype.toLowerCase(); if (FileUpload.isMultipartContent(req)) { callMethodForMultiPart(req, resp); } else if (MIME_JSON.equals(ctype)) { // TODO: json-rpc } else { callMethodForParam(req, resp); } } catch (Exception e) { e.printStackTrace(); throw new ServletException(e); } }
@Override public void setContent(InputStream inputStream) throws IOException { if (fileUpload instanceof MemoryFileUpload) { // change to Disk fileUpload = new DiskFileUpload( fileUpload.getName(), fileUpload.getFilename(), fileUpload.getContentType(), fileUpload.getContentTransferEncoding(), fileUpload.getCharset(), definedSize); } fileUpload.setContent(inputStream); }
@Override public void addContent(ChannelBuffer buffer, boolean last) throws IOException { if (fileUpload instanceof MemoryFileUpload) { if (fileUpload.length() + buffer.readableBytes() > limitSize) { DiskFileUpload diskFileUpload = new DiskFileUpload( fileUpload.getName(), fileUpload.getFilename(), fileUpload.getContentType(), fileUpload.getContentTransferEncoding(), fileUpload.getCharset(), definedSize); if (((MemoryFileUpload) fileUpload).getChannelBuffer() != null) { diskFileUpload.addContent(((MemoryFileUpload) fileUpload).getChannelBuffer(), last); } fileUpload = diskFileUpload; } } fileUpload.addContent(buffer, last); }
@Override public void setContent(ChannelBuffer buffer) throws IOException { if (buffer.readableBytes() > limitSize) { if (fileUpload instanceof MemoryFileUpload) { // change to Disk fileUpload = new DiskFileUpload( fileUpload.getName(), fileUpload.getFilename(), fileUpload.getContentType(), fileUpload.getContentTransferEncoding(), fileUpload.getCharset(), definedSize); } } fileUpload.setContent(buffer); }
@Override public void setContent(File file) throws IOException { if (file.length() > limitSize) { if (fileUpload instanceof MemoryFileUpload) { // change to Disk fileUpload = new DiskFileUpload( fileUpload.getName(), fileUpload.getFilename(), fileUpload.getContentType(), fileUpload.getContentTransferEncoding(), fileUpload.getCharset(), definedSize); } } fileUpload.setContent(file); }
protected void encodeInputField(FacesContext context, FileUpload fileUpload, String clientId) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.startElement("input", null); writer.writeAttribute("type", "file", null); writer.writeAttribute("id", clientId, null); writer.writeAttribute("name", clientId, null); if (fileUpload.isMultiple()) writer.writeAttribute("multiple", "multiple", null); if (fileUpload.getStyle() != null) writer.writeAttribute("style", fileUpload.getStyle(), "style"); if (fileUpload.getStyleClass() != null) writer.writeAttribute("class", fileUpload.getStyleClass(), "styleClass"); if (fileUpload.isDisabled()) writer.writeAttribute("disabled", "disabled", "disabled"); writer.endElement("input"); }
@Override public Charset getCharset() { return fileUpload.getCharset(); }
protected void encodeScript(FacesContext context, FileUpload fileUpload) throws IOException { String clientId = fileUpload.getClientId(context); String update = fileUpload.getUpdate(); String process = fileUpload.getProcess(); WidgetBuilder wb = getWidgetBuilder(context); if (fileUpload.getMode().equals("advanced")) { wb.initWithDomReady("FileUpload", fileUpload.resolveWidgetVar(), clientId); wb.attr("auto", fileUpload.isAuto(), false) .attr("dnd", fileUpload.isDragDropSupport(), true) .attr( "update", SearchExpressionFacade.resolveClientIds( context, fileUpload, update, SearchExpressionFacade.Options.VISIT_UNRENDERED), null) .attr( "process", SearchExpressionFacade.resolveClientIds( context, fileUpload, process, SearchExpressionFacade.Options.VISIT_UNRENDERED), null) .attr("maxFileSize", fileUpload.getSizeLimit(), Long.MAX_VALUE) .attr("fileLimit", fileUpload.getFileLimit(), Integer.MAX_VALUE) .attr("invalidFileMessage", fileUpload.getInvalidFileMessage(), null) .attr("invalidSizeMessage", fileUpload.getInvalidSizeMessage(), null) .attr("fileLimitMessage", fileUpload.getFileLimitMessage(), null) .attr("messageTemplate", fileUpload.getMessageTemplate(), null) .attr("previewWidth", fileUpload.getPreviewWidth(), 80) .attr("disabled", fileUpload.isDisabled(), false) .attr("sequentialUploads", fileUpload.isSequential(), false) .callback("onstart", "function()", fileUpload.getOnstart()) .callback("onerror", "function()", fileUpload.getOnerror()) .callback("oncomplete", "function(args)", fileUpload.getOncomplete()); if (fileUpload.getAllowTypes() != null) { wb.append(",allowTypes:").append(fileUpload.getAllowTypes()); } } else { wb.init("SimpleFileUpload", fileUpload.resolveWidgetVar(), clientId) .attr("skinSimple", fileUpload.isSkinSimple(), false); } wb.finish(); }
@Override public File getFile() throws IOException { return fileUpload.getFile(); }
protected void encodeSimpleMarkup(FacesContext context, FileUpload fileUpload) throws IOException { ResponseWriter writer = context.getResponseWriter(); String clientId = fileUpload.getClientId(context); String style = fileUpload.getStyle(); String styleClass = fileUpload.getStyleClass(); if (fileUpload.isSkinSimple()) { styleClass = (styleClass == null) ? FileUpload.CONTAINER_CLASS_SIMPLE : FileUpload.CONTAINER_CLASS_SIMPLE + " " + styleClass; String label = fileUpload.getLabel(); String buttonClass = isValueBlank(label) ? HTML.BUTTON_ICON_ONLY_BUTTON_CLASS : HTML.BUTTON_TEXT_ICON_LEFT_BUTTON_CLASS; if (fileUpload.isDisabled()) { buttonClass += " ui-state-disabled"; } writer.startElement("span", fileUpload); writer.writeAttribute("id", clientId, "id"); writer.writeAttribute("class", styleClass, "styleClass"); if (style != null) { writer.writeAttribute("style", style, "style"); } writer.startElement("span", null); writer.writeAttribute("class", buttonClass, null); // button icon writer.startElement("span", null); writer.writeAttribute("class", HTML.BUTTON_LEFT_ICON_CLASS + " ui-icon-plusthick", null); writer.endElement("span"); // text writer.startElement("span", null); writer.writeAttribute("id", clientId + "_label", null); writer.writeAttribute("class", HTML.BUTTON_TEXT_CLASS, null); if (isValueBlank(label)) { writer.write("ui-button"); } else { writer.writeText(label, "value"); } writer.endElement("span"); encodeInputField(context, fileUpload, fileUpload.getClientId(context)); writer.endElement("span"); writer.startElement("span", fileUpload); writer.writeAttribute("class", FileUpload.FILENAME_CLASS, null); writer.endElement("span"); writer.endElement("span"); } else { encodeSimpleInputField( context, fileUpload, fileUpload.getClientId(context), style, styleClass); } }
@Override public void delete() { fileUpload.delete(); }
@RequestMapping(method = RequestMethod.POST) public String onSubmit(FileUpload fileUpload, BindingResult errors, HttpServletRequest request) throws Exception { if (validator != null) { // validator is null during testing validator.validate(fileUpload, errors); if (errors.hasErrors()) { return "uploadForm"; } } // validate a file was entered if (fileUpload.getFile().length == 0) { Object[] args = new Object[] {getText("uploadForm.file", request.getLocale())}; errors.rejectValue("file", "errors.required", args, "File"); return "uploadForm"; } MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file"); // the directory to upload to String uploadDir = getServletContext().getRealPath("/resources") + "/" + request.getRemoteUser() + "/"; // Create the directory if it doesn't exist File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } // retrieve the file data InputStream stream = file.getInputStream(); // write the file to the file specified OutputStream bos = new FileOutputStream(uploadDir + file.getOriginalFilename()); int bytesRead; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); // close the stream stream.close(); // place the data into the request for retrieval on next page request.setAttribute("friendlyName", fileUpload.getName()); request.setAttribute("fileName", file.getOriginalFilename()); request.setAttribute("contentType", file.getContentType()); request.setAttribute("size", file.getSize() + " bytes"); request.setAttribute( "location", dirPath.getAbsolutePath() + Constants.FILE_SEP + file.getOriginalFilename()); String link = request.getContextPath() + "/resources" + "/" + request.getRemoteUser() + "/"; request.setAttribute("link", link + file.getOriginalFilename()); return getSuccessView(); }
@Override public String getContentTransferEncoding() { return fileUpload.getContentTransferEncoding(); }
@Override public byte[] get() throws IOException { return fileUpload.get(); }
/** * Read a FileUpload data as Byte (Binary) and add the bytes directly to the FileUpload. If the * delimiter is found, the FileUpload is completed. * * @param delimiter * @throws NotEnoughDataDecoderException Need more chunks but do not reset the readerInder since * some values will be already added to the FileOutput * @throws ErrorDataDecoderException write IO error occurs with the FileUpload */ private void readFileUploadByteMultipart(String delimiter) throws NotEnoughDataDecoderException, ErrorDataDecoderException { int readerIndex = undecodedChunk.readerIndex(); // found the decoder limit boolean newLine = true; int index = 0; int lastPosition = undecodedChunk.readerIndex(); boolean found = false; while (undecodedChunk.readable()) { byte nextByte = undecodedChunk.readByte(); if (newLine) { // Check the delimiter if (nextByte == delimiter.codePointAt(index)) { index++; if (delimiter.length() == index) { found = true; break; } continue; } else { newLine = false; index = 0; // continue until end of line if (nextByte == HttpCodecUtil.CR) { if (undecodedChunk.readable()) { nextByte = undecodedChunk.readByte(); if (nextByte == HttpCodecUtil.LF) { newLine = true; index = 0; lastPosition = undecodedChunk.readerIndex() - 2; } } } else if (nextByte == HttpCodecUtil.LF) { newLine = true; index = 0; lastPosition = undecodedChunk.readerIndex() - 1; } else { // save last valid position lastPosition = undecodedChunk.readerIndex(); } } } else { // continue until end of line if (nextByte == HttpCodecUtil.CR) { if (undecodedChunk.readable()) { nextByte = undecodedChunk.readByte(); if (nextByte == HttpCodecUtil.LF) { newLine = true; index = 0; lastPosition = undecodedChunk.readerIndex() - 2; } } } else if (nextByte == HttpCodecUtil.LF) { newLine = true; index = 0; lastPosition = undecodedChunk.readerIndex() - 1; } else { // save last valid position lastPosition = undecodedChunk.readerIndex(); } } } ChannelBuffer buffer = undecodedChunk.slice(readerIndex, lastPosition - readerIndex); if (found) { // found so lastPosition is correct and final try { currentFileUpload.addContent(buffer, true); // just before the CRLF and delimiter undecodedChunk.readerIndex(lastPosition); } catch (IOException e) { throw new ErrorDataDecoderException(e); } } else { // possibly the delimiter is partially found but still the last position is OK try { currentFileUpload.addContent(buffer, false); // last valid char (not CR, not LF, not beginning of delimiter) undecodedChunk.readerIndex(lastPosition); throw new NotEnoughDataDecoderException(); } catch (IOException e) { throw new ErrorDataDecoderException(e); } } }
@Override public ChannelBuffer getChannelBuffer() throws IOException { return fileUpload.getChannelBuffer(); }
/** * Get the FileUpload (new one or current one) * * @param delimiter the delimiter to use * @return the InterfaceHttpData if any * @throws ErrorDataDecoderException */ private InterfaceHttpData getFileUpload(String delimiter) throws ErrorDataDecoderException { // eventually restart from existing FileUpload // Now get value according to Content-Type and Charset Attribute encoding = currentFieldAttributes.get(HttpHeaders.Names.CONTENT_TRANSFER_ENCODING); Charset localCharset = charset; // Default TransferEncodingMechanism mechanism = TransferEncodingMechanism.BIT7; if (encoding != null) { String code; try { code = encoding.getValue().toLowerCase(); } catch (IOException e) { throw new ErrorDataDecoderException(e); } if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT7.value)) { localCharset = HttpPostBodyUtil.US_ASCII; } else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BIT8.value)) { localCharset = HttpPostBodyUtil.ISO_8859_1; mechanism = TransferEncodingMechanism.BIT8; } else if (code.equals(HttpPostBodyUtil.TransferEncodingMechanism.BINARY.value)) { // no real charset, so let the default mechanism = TransferEncodingMechanism.BINARY; } else { throw new ErrorDataDecoderException("TransferEncoding Unknown: " + code); } } Attribute charsetAttribute = currentFieldAttributes.get(HttpHeaders.Values.CHARSET); if (charsetAttribute != null) { try { localCharset = Charset.forName(charsetAttribute.getValue()); } catch (IOException e) { throw new ErrorDataDecoderException(e); } } if (currentFileUpload == null) { Attribute filenameAttribute = currentFieldAttributes.get(HttpPostBodyUtil.FILENAME); Attribute nameAttribute = currentFieldAttributes.get(HttpPostBodyUtil.NAME); Attribute contentTypeAttribute = currentFieldAttributes.get(HttpHeaders.Names.CONTENT_TYPE); if (contentTypeAttribute == null) { throw new ErrorDataDecoderException("Content-Type is absent but required"); } Attribute lengthAttribute = currentFieldAttributes.get(HttpHeaders.Names.CONTENT_LENGTH); long size; try { size = lengthAttribute != null ? Long.parseLong(lengthAttribute.getValue()) : 0L; } catch (IOException e) { throw new ErrorDataDecoderException(e); } catch (NumberFormatException e) { size = 0; } try { currentFileUpload = factory.createFileUpload( request, nameAttribute.getValue(), filenameAttribute.getValue(), contentTypeAttribute.getValue(), mechanism.value, localCharset, size); } catch (NullPointerException e) { throw new ErrorDataDecoderException(e); } catch (IllegalArgumentException e) { throw new ErrorDataDecoderException(e); } catch (IOException e) { throw new ErrorDataDecoderException(e); } } // load data as much as possible try { readFileUploadByteMultipart(delimiter); } catch (NotEnoughDataDecoderException e) { // do not change the buffer position // since some can be already saved into FileUpload // So do not change the currentStatus return null; } if (currentFileUpload.isCompleted()) { // ready to load the next one if (currentStatus == MultiPartStatus.FILEUPLOAD) { currentStatus = MultiPartStatus.HEADERDELIMITER; currentFieldAttributes = null; } else { currentStatus = MultiPartStatus.MIXEDDELIMITER; cleanMixedAttributes(); } FileUpload fileUpload = currentFileUpload; currentFileUpload = null; return fileUpload; } // do not change the buffer position // since some can be already saved into FileUpload // So do not change the currentStatus return null; }
@Override public String getContentType() { return fileUpload.getContentType(); }