Get filename from content disposition in header.

@param url url of current file to download
@param contentDisposition content disposition in header
@return filename in header if existed, otherwise get from url
167378
public static String getFilenameFromHeader(String url, String contentDisposition) {
    String filename;
    if (!TextUtils.isEmpty(contentDisposition)) {
      int index = contentDisposition.indexOf("filename");
      if (index > 0) {
        filename = contentDisposition.substring(index + 9, contentDisposition.length());
        return filename;
      } else {
        filename = getFilenameFromUrl(url);
      }
    } else {
      filename = getFilenameFromUrl(url);
    }

    try {
      filename = URLDecoder.decode(filename, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      /* ignore */
    }

    return filename;
  }
417196
private InterfaceHttpData findMultipartDisposition() {
        int readerIndex = undecodedChunk.readerIndex();
        if (currentStatus == MultiPartStatus.DISPOSITION) {
            currentFieldAttributes = new TreeMap<CharSequence, Attribute>(CaseIgnoringComparator.INSTANCE);
        }
        // read many lines until empty line with newline found! Store all data
        while (!skipOneLine()) {
            String newline;
            try {
                skipControlCharacters(undecodedChunk);
                newline = readLine(undecodedChunk, charset);
            } catch (NotEnoughDataDecoderException ignored) {
                undecodedChunk.readerIndex(readerIndex);
                return null;
            }
            String[] contents = splitMultipartHeader(newline);
            if (HttpHeaderNames.CONTENT_DISPOSITION.contentEqualsIgnoreCase(contents[0])) {
                boolean checkSecondArg;
                if (currentStatus == MultiPartStatus.DISPOSITION) {
                    checkSecondArg = HttpHeaderValues.FORM_DATA.contentEqualsIgnoreCase(contents[1]);
                } else {
                    checkSecondArg = HttpHeaderValues.ATTACHMENT.contentEqualsIgnoreCase(contents[1])
                            || HttpHeaderValues.FILE.contentEqualsIgnoreCase(contents[1]);
                }
                if (checkSecondArg) {
                    // read next values and store them in the map as Attribute
                    for (int i = 2; i < contents.length; i++) {
                        String[] values = contents[i].split("=", 2);
                        Attribute attribute;
                        try {
                            attribute = getContentDispositionAttribute(values);
                        } catch (NullPointerException e) {
                            throw new ErrorDataDecoderException(e);
                        } catch (IllegalArgumentException e) {
                            throw new ErrorDataDecoderException(e);
                        }
                        currentFieldAttributes.put(attribute.getName(), attribute);
                    }
                }
            } else if (HttpHeaderNames.CONTENT_TRANSFER_ENCODING.contentEqualsIgnoreCase(contents[0])) {
                Attribute attribute;
                try {
                    attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_TRANSFER_ENCODING.toString(),
                            cleanString(contents[1]));
                } catch (NullPointerException e) {
                    throw new ErrorDataDecoderException(e);
                } catch (IllegalArgumentException e) {
                    throw new ErrorDataDecoderException(e);
                }

                currentFieldAttributes.put(HttpHeaderNames.CONTENT_TRANSFER_ENCODING, attribute);
            } else if (HttpHeaderNames.CONTENT_LENGTH.contentEqualsIgnoreCase(contents[0])) {
                Attribute attribute;
                try {
                    attribute = factory.createAttribute(request, HttpHeaderNames.CONTENT_LENGTH.toString(),
                            cleanString(contents[1]));
                } catch (NullPointerException e) {
                    throw new ErrorDataDecoderException(e);
                } catch (IllegalArgumentException e) {
                    throw new ErrorDataDecoderException(e);
                }

                currentFieldAttributes.put(HttpHeaderNames.CONTENT_LENGTH, attribute);
            } else if (HttpHeaderNames.CONTENT_TYPE.contentEqualsIgnoreCase(contents[0])) {
                // Take care of possible "multipart/mixed"
                if (HttpHeaderValues.MULTIPART_MIXED.contentEqualsIgnoreCase(contents[1])) {
                    if (currentStatus == MultiPartStatus.DISPOSITION) {
                        String values = StringUtil.substringAfter(contents[2], '=');
                        multipartMixedBoundary = "--" + values;
                        currentStatus = MultiPartStatus.MIXEDDELIMITER;
                        return decodeMultipart(MultiPartStatus.MIXEDDELIMITER);
                    } else {
                        throw new ErrorDataDecoderException("Mixed Multipart found in a previous Mixed Multipart");
                    }
                } else {
                    for (int i = 1; i < contents.length; i++) {
                        final String charsetHeader = HttpHeaderValues.CHARSET.toString();
                        if (contents[i].regionMatches(true, 0, charsetHeader, 0, charsetHeader.length())) {
                            String values = StringUtil.substringAfter(contents[i], '=');
                            Attribute attribute;
                            try {
                                attribute = factory.createAttribute(request, charsetHeader, cleanString(values));
                            } catch (NullPointerException e) {
                                throw new ErrorDataDecoderException(e);
                            } catch (IllegalArgumentException e) {
                                throw new ErrorDataDecoderException(e);
                            }
                            currentFieldAttributes.put(HttpHeaderValues.CHARSET, attribute);
                        } else {
                            Attribute attribute;
                            try {
                                attribute = factory.createAttribute(request,
                                        cleanString(contents[0]), contents[i]);
                            } catch (NullPointerException e) {
                                throw new ErrorDataDecoderException(e);
                            } catch (IllegalArgumentException e) {
                                throw new ErrorDataDecoderException(e);
                            }
                            currentFieldAttributes.put(attribute.getName(), attribute);
                        }
                    }
                }
            } else {
                throw new ErrorDataDecoderException("Unknown Params: " + newline);
            }
        }
        // Is it a FileUpload
        Attribute filenameAttribute = currentFieldAttributes.get(HttpHeaderValues.FILENAME);
        if (currentStatus == MultiPartStatus.DISPOSITION) {
            if (filenameAttribute != null) {
                // FileUpload
                currentStatus = MultiPartStatus.FILEUPLOAD;
                // do not change the buffer position
                return decodeMultipart(MultiPartStatus.FILEUPLOAD);
            } else {
                // Field
                currentStatus = MultiPartStatus.FIELD;
                // do not change the buffer position
                return decodeMultipart(MultiPartStatus.FIELD);
            }
        } else {
            if (filenameAttribute != null) {
                // FileUpload
                currentStatus = MultiPartStatus.MIXEDFILEUPLOAD;
                // do not change the buffer position
                return decodeMultipart(MultiPartStatus.MIXEDFILEUPLOAD);
            } else {
                // Field is not supported in MIXED mode
                throw new ErrorDataDecoderException("Filename not found");
            }
        }
    }
218779
public static String getImageFilename(String strFilename, String strSubDirectory)
   {
       if ((strFilename == null) || (strFilename.length() == 0))
           return null;    // A null will tell a JButton not to load an image
       if (strFilename.indexOf('.') == -1)
           strFilename += ".gif";
       strFilename = Util.getFullFilename(strFilename, strSubDirectory, Constant.IMAGE_LOCATION, true);
       return strFilename;
   }
1265537
protected static String getResourceName(CmsObject cms, I_CmsResourceContainer contentContainer) {

        if ((contentContainer != null) && (contentContainer.getResourceName() != null)) {
            return contentContainer.getResourceName();
        } else if (cms != null) {
            return cms.getRequestContext().getUri();
        } else {
            return null;
        }
    }
1132696
def parse_headers(content_disposition, location=None, relaxed=False):
    

    LOGGER.debug(
        'Content-Disposition %r, Location %r', content_disposition, location)

    if content_disposition is None:
        return ContentDisposition(location=location)

    # Both alternatives seem valid.
    if False:
        # Require content_disposition to be ascii bytes (0-127),
        # or characters in the ascii range
        content_disposition = ensure_charset(content_disposition, 'ascii')
    else:
        # We allow non-ascii here (it will only be parsed inside of
        # qdtext, and rejected by the grammar if it appears in
        # other places), although parsing it can be ambiguous.
        # Parsing it ensures that a non-ambiguous filename* value
        # won't get dismissed because of an unrelated ambiguity
        # in the filename parameter. But it does mean we occasionally
        # give less-than-certain values for some legacy senders.
        content_disposition = ensure_charset(content_disposition, 'iso-8859-1')

    # Check the caller already did LWS-folding (normally done
    # when separating header names and values; RFC 2616 section 2.2
    # says it should be done before interpretation at any rate).
    # Hopefully space still means what it should in iso-8859-1.
    # This check is a bit stronger that LWS folding, it will
    # remove CR and LF even if they aren't part of a CRLF.
    # However http doesn't allow isolated CR and LF in headers outside
    # of LWS.

    if relaxed:
        # Relaxed has two effects (so far):
        # the grammar allows a final ';' in the header;
        # we do LWS-folding, and possibly normalise other broken
        # whitespace, instead of rejecting non-lws-safe text.
        # XXX Would prefer to accept only the quoted whitespace
        # case, rather than normalising everything.
        content_disposition = normalize_ws(content_disposition)
        parser = content_disposition_value_relaxed
    else:
        # Turns out this is occasionally broken: two spaces inside
        # a quoted_string's qdtext. Firefox and Chrome save the two spaces.
        if not is_lws_safe(content_disposition):
            raise ValueError(
                content_disposition, 'Contains nonstandard whitespace')

        parser = content_disposition_value

    try:
        parsed = parser.parse(content_disposition)
    except FullFirstMatchException:
        return ContentDisposition(location=location)
    return ContentDisposition(
        disposition=parsed[0], assocs=parsed[1:], location=location)
588196
def get_content_disposition_filename(self, private_file):
        
        return self.content_disposition_filename or os.path.basename(private_file.relative_name)
506130
public static void initFileSendHeader(HttpServletResponse res, String filename, String contentType) {

        filename = getEncodingFileName(filename);
        if (contentType != null) {
            res.setContentType(contentType);
        } else {
            res.setContentType("applicaiton/download;charset=utf-8");
        }
        res.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\";");
        res.setHeader("Content-Transfer-Encoding", "binary");
        res.setHeader("file-name", filename);

    }
945975
private static function get_filename_from_url( $url ) {
		$url_parts   = explode( '/', $url );
		$parts_count = count( $url_parts );
		if ( 1 < $parts_count ) {
			return $url_parts[ count( $url_parts ) - 1 ];
		}
		return $url;
	}
485204
public String getContentType() {
    if (contentType != null) {
      return contentType;
    }

    if (dataStream != null) {
      try {
        contentType = URLConnection.guessContentTypeFromStream(dataStream);
      } catch (IOException ioe) {
        // ignore exception
      }
    }

    if (data != null) {
      contentType = URLConnection.guessContentTypeFromName(filename);
    }

    // fallback - if we have no contenttype and cannot detect one, use 'application/octet-stream'
    if (contentType == null) {
      contentType = "application/octet-stream";
    }

    return contentType;
  }
331703
public static String getFileName(TaskResponse response){
        List<String> name = response.header("content-disposition");
        System.out.println(name);
        if (null != name) {
            return Arrays.stream(name.get(0).split("; ")).filter(item -> {
                return item.trim().startsWith("filename=\"");
            }).map(filename -> {
                return filename.replaceAll("filename=","").replaceAll("\"","");
            }).limit(1).collect(Collectors.toList()).get(0);
        }
        return null;
    }
233622
@Nullable
  private static String _getFilename (@Nullable final String sContentDisposition)
  {
    String sFilename = null;
    if (sContentDisposition != null)
    {
      final String sContentDispositionLC = sContentDisposition.toLowerCase (Locale.US);
      if (sContentDispositionLC.startsWith (RequestHelper.FORM_DATA) ||
          sContentDispositionLC.startsWith (RequestHelper.ATTACHMENT))
      {
        // Parameter parser can handle null input
        final ICommonsMap <String, String> aParams = new ParameterParser ().setLowerCaseNames (true)
                                                                           .parse (sContentDisposition, ';');
        if (aParams.containsKey ("filename"))
        {
          sFilename = aParams.get ("filename");
          if (sFilename != null)
          {
            sFilename = sFilename.trim ();
          }
          else
          {
            // Even if there is no value, the parameter is present,
            // so we return an empty file name rather than no file
            // name.
            sFilename = "";
          }
        }
      }
    }
    return sFilename;
  }
1199836
function getFilename(){
		if($content_disposition = $this->getHeaderValue("Content-Disposition")){
			if(preg_match('/filename="(.*?)"/',$content_disposition,$matches)){
				return $matches[1];
			}
		}
		if(preg_match("/([^\\/?]+)(\\?.*|)$/",$this->_Uri,$matches)){
			return $matches[1];
		}
	}
380409
public Response filenameHeader(String filename) {
        if (filename != null && !filename.isEmpty()) {
            header(HttpConstants.Header.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"");
        } else {
            header(HttpConstants.Header.CONTENT_DISPOSITION, "attachment; filename=\"\"");
        }

        return this;
    }
1067660
@Pure
	@SuppressWarnings("checkstyle:npathcomplexity")
	public static URL dirname(URL filename) {
		if (filename == null) {
			return null;
		}

		URL prefix = null;
		String path;
		if (isJarURL(filename)) {
			prefix = getJarURL(filename);
			path = fromFileStandardToURLStandard(getJarFile(filename));
		} else {
			path = filename.getPath();
		}

		if ("".equals(path)) { //$NON-NLS-1$
			return null;
		}

		int idx = path.lastIndexOf(URL_PATH_SEPARATOR_CHAR);
		if (idx == path.length() - 1) {
			idx = path.lastIndexOf(URL_PATH_SEPARATOR_CHAR, path.length() - 2);
		}

		if (idx < 0) {
			if (URISchemeType.getSchemeType(filename).isFileBasedScheme()) {
				path = CURRENT_DIRECTORY;
			} else {
				path = URL_PATH_SEPARATOR;
			}
		} else {
			path = path.substring(0, idx + 1);
		}

		try {
			if (prefix != null) {
				return toJarURL(prefix, path);
			}
			return new URI(filename.getProtocol(),
					filename.getUserInfo(),
					filename.getHost(),
					filename.getPort(),
					decodeHTMLEntities(path),
					null,
					null).toURL();
		} catch (Throwable exception) {
			//
		}

		try {
			return new URL(
					filename.getProtocol(),
					filename.getHost(),
					path);
		} catch (Throwable exception) {
			//
		}
		return null;
	}
217370
public static File getCanonicalFileFromFileUrl(final URL url) {
        File file = null;
        if (url == null) {
            throw new NullPointerException("The URL cannot be null.");
        }
        if ("file".equals(url.getProtocol())) {
            final String fileName = url.getFile();
            final String path = URLUtils.uncorrect(fileName);
            file = new File(path);

            try {
                file = file.getCanonicalFile();
            } catch (final IOException e) {
                // Does not exist.
                file = file.getAbsoluteFile();
            }

        }
        return file;
    }
184833
private String getFileName(MultivaluedMap<String, String> header) {

		String[] contentDisposition = header.getFirst("Content-Disposition").split(";");

		for (String filename : contentDisposition) {
			if ((filename.trim().startsWith("filename"))) {

				String[] name = filename.split("=");

				String finalFileName = name[1].trim().replaceAll("\"", "");
				return finalFileName;
			}
		}
		return "unknown";
	}
452075
public String getSubmittedFileName() {
        // TODO this method also introduced in servlet 3.1 specification (delegate to part when I adopt servlet 3.1)
        if (submittedFileName == null) {
            String header = part.getHeader(HttpConstants.Header.CONTENT_DISPOSITION);
            if (header == null) {
                return null;
            }

            for (String headerPart : header.split(";")) {
                if (headerPart.trim().startsWith("filename")) {
                    submittedFileName = headerPart.substring(headerPart.indexOf('=') + 1).trim().replace("\"", "");
                    break;
                }
            }
        }

        return submittedFileName;
    }