Estou escrevendo um servidor web simples em python que permite ao usuário carregar um arquivo usando multipart / form-data. Tanto quanto eu posso dizer, multipart MIME dados é suposto ser linha baseada. Por exemplo, o limite tem de estar no início de uma linha. Eu não consigo descobrir como os dados binários são tratados a este respeito. Meu cliente (Firefox) não está codificando em 7 bits ASCII ou qualquer coisa, seus dados binários apenas raw seu envio. Será que dividir os dados em linhas em locais arbitrários Existe um comprimento de linha máximo especificado para dados de várias partes Ive tentou olhar através do RFC para multipart / form-data, mas não encontrou nada. Perguntou Mar 27 13 at 16:54 Depois de cavar através dos RFCs, acho que finalmente consegui tudo direto na minha cabeça. As partes do corpo (isto é, o conteúdo do corpo de uma parte individual numa multipart / mensagem) apenas precisam de ser baseadas em linhas, uma vez que o limite no final da parte começa com um CRLF. Mas, caso contrário, os dados não precisam ser baseados em linha, e se o conteúdo acontece com linebreaks nele, não há distância máxima entre eles, nem eles precisam ser escapados de qualquer maneira (bem, a menos que talvez o Content-Transfer - A codificação é quoted-string). As opções de 7 bits, 8 bits e binárias para Content-Transfer-Encoding não indicam realmente que qualquer codificação foi feita nos dados (e, portanto, nenhuma codificação precisa ser desfeita), eles significam apenas para indicar o tipo de dados Você pode esperar para ver na parte do corpo. O que eu estava realmente começando em minha pergunta mal expressa era como ler / buffer os dados do soquete para que eu pudesse ter certeza que eu peguei o limite, e sem ter que ter um buffer arbitrariamente grande (por exemplo, se aconteceu de ser não Linebreaks no conteúdo, e assim um readline acabou buffering a coisa toda). O que eu acabei fazendo foi buffer do soquete com um readline usando um comprimento máximo, então o buffer nunca seria mais longo do que isso, mas também iria certificar-se de terminar se um linebreak foi encontrado. Isso garantiu que quando o limite veio (após um CRLF), seria no início do buffer. Eu tive que fazer um pouco de monkeying extra ao redor para garantir que eu não incluíram que CRLF final no conteúdo real do corpo, porque de acordo com o RFC é necessário antes da fronteira e, portanto, não parte do conteúdo em si. Resposta Tente rever o RFC 2045. Normalmente, o conteúdo binário é convertido em BASE64 pela sua aplicação e incluído na mensagem de várias partes usando Content-Transfer-Encoding. Base64. Existem outros mecanismos para transferir dados binários, mas isso é bastante comum. Os dados binários são convertidos em octetos e fragmentados em cadeias de comprimento arbitrárias (dependendo da variante de codificação - veja o link BASE64 acima). O aplicativo receptor, em seguida, decodifica-lo para o conteúdo binário original. Eu não sou um programador python, mas eu ficaria surpreso que você realmente tinha que codificar qualquer um deste você mesmo. Eu suspeito que existem funções pré-construídas da biblioteca python para fazer isso por você. Resposta Apesar da flexibilidade, interoperabilidade e aceitação global do XML, há momentos em que a serialização de dados em XML não faz sentido. Os usuários de serviços da Web podem querer transmitir anexos binários de vários tipos, como imagens, desenhos, documentos XML, etc., juntamente com uma mensagem SOAP. Esses dados são freqüentemente em um formato binário particular. Tradicionalmente, duas técnicas têm sido usadas no tratamento de dados opacos em XML. Enviar dados binários por valor é obtido incorporando dados opacos (obviamente após alguma forma de codificação) como um elemento ou conteúdo de atributo do componente XML de dados. A principal vantagem desta técnica é que dá aos aplicativos a capacidade de processar e descrever dados, com base apenas no componente XML dos dados. O XML suporta dados opacos como conteúdo através do uso de codificação de texto base64 ou hexadecimal. Ambas as técnicas enfraquecem o tamanho dos dados. Para a codificação de texto subjacente ao UTF-8, a codificação base64 aumenta o tamanho dos dados binários por um fator de 1,33x do tamanho original, enquanto a codificação hexadecimal expande dados por um fator de 2x. Os fatores acima serão duplicados se a codificação de texto UTF-16 for usada. Também é preocupante a sobrecarga nos custos de processamento (real e percebido) para esses formatos, especialmente quando a decodificação volta para o binário bruto. O envio de dados binários por referência é conseguido anexando dados binários puros como entidades externas não segmentadas externas ao documento XML e incorporando URIs de referência a essas entidades como elementos ou valores de atributo. Isso evita o inchaço desnecessário de dados e desperdício de poder de processamento. O principal obstáculo para o uso dessas entidades não analisadas é a sua grande dependência de DTDs, o que impede a modularidade, bem como o uso de namespaces XML. Havia várias especificações introduzidas no mundo dos serviços da Web para lidar com esse problema de anexação binária usando a técnica quotby referencequot. SOAP with Attachments é um exemplo. Como o SOAP proíbe declarações de tipo de documento (DTD) em mensagens, isso leva ao problema de não representar dados como parte da mensagem infoset, criando, portanto, dois modelos de dados. Esse cenário é como enviar anexos com uma mensagem de email. Mesmo que esses anexos estejam relacionados ao conteúdo da mensagem eles não estão dentro da mensagem. Isso faz com que as tecnologias que processam e descrevem os dados com base no componente XML dos dados com mau funcionamento. Um exemplo é o WS-Security. Onde MTOM vem em MTOM (SOAP Message Transmission Optimization Mechanism) é outra especificação que se concentra em resolver o quotAttachmentsquot problema. MTOM tenta aproveitar as vantagens das duas técnicas acima, tentando mesclar as duas técnicas. MTOM é na verdade um método de referência quotby. O formato de fio de uma mensagem otimizada MTOM é o mesmo que a mensagem SOAP com anexos, que também torna compatível com Swa endpoints. A característica mais notável do MTOM é o uso do elemento XOP: Include, que é definido na especificação XOP (XML Binary Optimized Packaging) para fazer referência aos anexos binários (entidades gerais externas não analisadas) da mensagem. Com o uso deste elemento exclusivo, o conteúdo binário anexado logicamente torna-se inline (por valor) com o documento SOAP, mesmo que ele realmente é anexado separadamente. Isso funde os dois domínios, tornando possível trabalhar apenas com um modelo de dados. Isso permite que as aplicações processem e descrevam apenas olhando para a parte XML, tornando obsoleta a dependência de DTDs. Em uma nota mais leve, MTOM tem padronizado o mecanismo de referência SwA. O seguinte é um extrato da especificação XOP. No nível conceitual, esses dados binários podem ser considerados base64-codificados no documento XML. Como essa forma conceitual pode ser necessária durante algum processamento do documento XML (por exemplo, para assinar o documento XML), é necessário ter uma correspondência um-para-um entre os conjuntos de informações XML e os pacotes XOP. Portanto, a representação conceitual de tais dados binários é como se fosse codificada em base64, usando a forma léxica canônica do tipo de dados base64Binary Schema XML (consulte XML Schema Parte 2: Datatypes Second Edition 3.2.16 base64Binary). Na direção inversa, XOP é capaz de otimizar apenas dados de Infoset codificados em base64 que estão na forma lexical canônica. Apache Axis2 suporta a codificação Base64. SOAP com anexos e MTOM (mecanismo de optimização de transmissão de mensagens SOAP). MTOM com Modelo de Programação Axis2 AXIOM é (e pode ser o primeiro) Modelo de Objeto que tem a capacidade de armazenar dados binários. Ele tem essa capacidade como OMText pode conter conteúdo binário bruto na forma de javax. activation. DataHandler. OMText foi escolhido para este fim com duas razões. Uma delas é que o XOP (MTOM) é capaz de otimizar apenas dados de Infoset codificados em base64 que estão na forma léxica canônica do tipo de dados base64Binary Schema XML. Outro é preservar o infoset tanto no remetente como no receptor. (Para armazenar o conteúdo binário no mesmo tipo de objeto, independentemente de estar otimizado ou não). O MTOM permite codificar seletivamente porções da mensagem, o que nos permite enviar dados baseados em código base, bem como dados binários brutos conectados externamente, referenciados pelo elemento quotXOPquot (conteúdo otimizado) para ser enviado em uma mensagem SOAP. Você pode especificar se um nó OMText que contém dados binários brutos ou dados binários base64encoded está qualificado para ser otimizado no momento da construção desse nó ou posterior. Para uma melhor eficiência do MTOM, um usuário é aconselhado a enviar anexos binários menores usando base64encoding (não otimizado) e anexos maiores como conteúdo otimizado. Além disso, um usuário pode criar um nó de conteúdo binário otimizável usando uma seqüência codificada em base64, que contém conteúdo binário codificado, fornecido com o tipo MIME da representação binária real. Axis2 usa javax. activation. DataHandler para manipular os dados binários. Todos os nós de conteúdo binário otimizados serão serializados como Cadeias de Base64 se quotMTOM não estiver ativadoquot. Você também pode criar nós de conteúdo binário, que não serão otimizados em qualquer caso. Eles serão serializados e enviados como Base64 Strings. Habilitando a otimização do MTOM no lado do cliente em Opções, defina a propriedade quotenableMTOMquot como True quando enviar mensagens. Quando essa propriedade é definida como True, qualquer envelope SOAP, independentemente de ele conter conteúdo otimizável ou não, será serializado como uma mensagem MIME otimizada MTOM. Axis2 serializa todos os nós de conteúdo binário como seqüências codificadas Base64 independentemente se eles são qualificados para ser otimizado ou não se a propriedade quotenableMTOMquot estiver definida como False. Se o envelope contiver qualquer item de informação do elemento do nome xop: Include (veja XML-binário Otimizado Embalagem 3. XOP Infosets Constructs). O usuário não precisa especificar nada para que o Axis2 receba mensagens MTOM otimizadas. Axis2 irá automaticamente identificar e des-serializar em conformidade, como e quando uma mensagem MTOM chega. Habilitando a otimização do MTOM no lado do servidor O servidor do Axis 2 identifica automaticamente mensagens MTOM recebidas de entrada com base no tipo de conteúdo e as desalifa adequadamente. O usuário pode habilitarMTOM no lado do servidor para mensagens de saída, Para habilitarMTOM globalmente para todos os serviços, os usuários podem definir o parâmetro quotenableMTOMquot como True no Axis2.xml. Quando estiver definido, todas as mensagens de saída serão serializadas e enviadas como mensagens MIME optimizadas MTOM. Se não estiver definido, todos os dados binários nos nós de conteúdo binário serão serializados como cadeias codificadas em Base64. Essa configuração pode ser substituída em services. xml com base em por serviço e por operação. Você deve reiniciar o servidor após a configuração desse parâmetro. O campo Content-Transfer-Encoding Header Muitos tipos de conteúdo que poderiam ser transportados via e-mail são representados, em seu formato natural, como caracteres de 8 bits ou dados binários. Esses dados não podem ser transmitidos através de alguns protocolos de transporte. Por exemplo, RFC 821 restringe mensagens de correio electrónico para 7-bit dados US-ASCII com 1000 caracteres linhas. É necessário, portanto, definir um mecanismo padrão para recodificar esses dados em um formato de linha curta de 7 bits. Este documento especifica que tais codificações serão indicadas por um novo cabeçalho Content-Transfer-Encoding campo. O campo Content-Transfer-Encoding é usado para indicar o tipo de transformação que foi usado para representar o corpo de forma aceitável para o transporte. Ao contrário dos tipos de conteúdo, uma proliferação de valores Content-Transfer-Encoding é indesejável e desnecessária. No entanto, o estabelecimento de apenas um único mecanismo Content-Transfer-Encoding não parece possível. Existe um compromisso entre o desejo de uma codificação compacta e eficiente de dados em grande parte binários e o desejo de uma codificação legível de dados que é na maior parte, mas não inteiramente, dados de 7 bits. Por esta razão, pelo menos dois mecanismos de codificação são necessários: uma codificação legível e uma codificação densa. O campo Content-Transfer-Encoding é projetado para especificar um mapeamento invertible entre a representação nativa de um tipo de dados e uma representação que pode ser facilmente trocada usando protocolos de transporte de correio de 7 bits, como os definidos pela RFC 821 (SMTP). Este campo não foi definido por qualquer padrão anterior. O valor de campos é um token único que especifica o tipo de codificação, conforme enumerado abaixo. Formalmente: Esses valores não são sensíveis a maiúsculas e minúsculas. Ou seja, Base64 e BASE64 e bAsE64 são todos equivalentes. Um tipo de codificação de 7BIT requer que o corpo já esteja em uma representação de sete bits pronta para envio. Esse é o valor padrão - ou seja, Content-Transfer-Encoding: 7BIT é assumido se o campo de cabeçalho Content-Transfer-Encoding não estiver presente. Os valores 8bit, 7bit e binário implicam que a codificação NO foi executada. No entanto, são potencialmente úteis como indicações do tipo de dados contidos no objecto e, portanto, do tipo de codificação que pode necessitar de ser executado para transmissão num dado sistema de transporte. 7bit significa que os dados são todos representados como linhas curtas de dados US-ASCII. 8bit significa que as linhas são curtas, mas pode haver caracteres não ASCII (octetos com o bit de ordem alta ajustado). Binário significa que não só pode não-caracteres ASCII estar presentes, mas também que as linhas não são necessariamente curtas o suficiente para o transporte SMTP. A diferença entre 8 bits (ou qualquer outro token de largura de bits concebível) e o token binário é que o binário não exige aderência a quaisquer limites de comprimento de linha ou à semântica SMTP CRLF, enquanto os tokens de largura de bit requerem tal aderência. Se o corpo contiver dados em qualquer largura de bit diferente de 7 bits, o token de Content-Transfer-Encoding de bit-width apropriado deve ser usado (por exemplo, 8 bits para dados não codificados de 8 bits de largura). Se o corpo contiver dados binários, o token binário Content-Transfer-Encoding deve ser usado. NOTA: A distinção entre os valores Content-Transfer-Encoding de binário, 8 bits, etc. pode parecer sem importância, na medida em que todos eles realmente significam nenhum - ou seja, não houve codificação dos dados para transporte. No entanto, a rotulagem clara será de enorme valor para gateways entre futuros sistemas de transporte de correio com capacidades diferentes no transporte de dados que não atendam às restrições do transporte RFC 821. Desde a publicação deste documento, não existem transportes Internet padronizados para os quais é legítimo incluir dados não codificados de 8 bits ou binários em corpos de correio. Assim, não há circunstâncias em que o 8bit ou binário Content-Transfer-Encoding é realmente legal na Internet. No entanto, no caso em que o transporte de 8 bits ou de correio binário se torna uma realidade no correio da Internet ou quando este documento é utilizado em conjunto com qualquer outro mecanismo de transporte de 8 bits ou binário, os corpos de 8 bits ou binários devem ser identificados Como tal utilizando este mecanismo. NOTA: Os cinco valores definidos para o campo Content-Transfer-Encoding não implicam nada sobre o Content-Type diferente do algoritmo pelo qual foi codificado ou os requisitos do sistema de transporte se não codificado. Os implementadores podem, se necessário, definir novos valores Content-Transfer-Encoding, mas devem usar um token x, que é um nome prefixado por X - para indicar seu status não padrão, p. Content-Transfer-Encoding: x-my-new-encoding. No entanto, ao contrário de Content-Types e subtipos, a criação de novos Content-Transfer-Encoding valores é explicitamente e fortemente desencorajados, pois parece ser susceptível de dificultar a interoperabilidade com pouco benefício potencial. A sua utilização é permitida apenas como resultado de um acordo entre agentes utilizadores que colaboram. Se um campo de cabeçalho Content-Transfer-Encoding aparece como parte de um cabeçalho de mensagem, ele se aplica a todo o corpo dessa mensagem. Se um campo de cabeçalho Content-Transfer-Encoding aparece como parte de um cabeçalho de partes do corpo, ele se aplica somente ao corpo dessa parte do corpo. Se uma entidade é do tipo multipart ou mensagem, o Content-Transfer-Encoding não tem permissão para ter qualquer valor diferente de uma largura de bit (por exemplo, 7bit, 8bit, etc.) ou binário. Deve-se notar que o e-mail é orientado a caracteres, de modo que os mecanismos descritos aqui são mecanismos para codificar fluxos de bytes arbitrários, não fluxos de bits. Se um fluxo de bits deve ser codificado por meio de um desses mecanismos, ele deve primeiro ser convertido em um fluxo de bytes de 8 bits usando a ordem de bits padrão da rede (big-endian), em que os bits anteriores em um fluxo tornam - Ordem bits em um byte. Um fluxo de bits que não termina em um limite de 8 bits deve ser preenchido com zeros. Este documento fornece um mecanismo para observar a adição de tal preenchimento no caso do aplicativo Content-Type, que tem um padding parâmetro. Os mecanismos de codificação aqui definidos explicitamente codificam todos os dados em ASCII. Assim, por exemplo, suponha que uma entidade tenha campos de cabeçalho como: Isto deve ser interpretado para significar que o corpo é uma codificação ASCII base64 de dados que estava originalmente em ISO-8859-1 e estará nesse conjunto de caracteres novamente após a descodificação . As seções a seguir definirão os dois mecanismos padrão de codificação. A definição de novas codificações de conteúdo-transferência é explicitamente desencorajada e só deve ocorrer quando absolutamente necessário. Todo o espaço de nomes de codificação de transferência de conteúdo exceto aquele começando com X - é explicitamente reservado à IANA para uso futuro. Os acordos privados sobre encoding de transferência de conteúdo também são explicitamente desencorajados. Determinados valores de Content-Transfer-Encoding só podem ser usados em determinados Content-Types. Em particular, é expressamente proibido usar qualquer codificação diferente de 7bit, 8bit ou binário com qualquer Content-Type que recursivamente inclua outros campos de Content-Type, notadamente o multipart e mensagem Content-Types. Todas as codificações que são desejadas para corpos de tipo multipart ou mensagem devem ser feitas no nível mais interno, codificando o corpo real que precisa ser codificado. OBSERVAÇÃO SOBRE AS RESTRIÇÕES DE CODIFICAÇÃO: Embora a proibição de usar codificações de transferência de conteúdo em dados de tipo multipart ou mensagem possa parecer excessivamente restritiva, é necessário evitar codificações aninhadas, nas quais os dados são passados por um algoritmo de codificação várias vezes e devem ser Decodificado várias vezes para ser visualizado corretamente. As codificações aninhadas agregam considerável complexidade aos agentes do usuário: além dos óbvios problemas de eficiência com tais codificações múltiplas, elas podem obscurecer a estrutura básica de uma mensagem. Em particular, eles podem implicar que várias operações de decodificação são necessárias simplesmente para descobrir quais tipos de objetos uma mensagem contém. A proibição de codificações aninhadas pode complicar o trabalho de determinados gateways de email, mas isso parece menos um problema do que o efeito de codificações aninhadas nos agentes do usuário. NOTA SOBRE A RELAÇÃO ENTRE TIPO DE CONTEÚDO E CONTEÚDO - TRANSFERÊNCIA-CODIFICAÇÃO Pode parecer que o Content-Transfer-Encoding poderia ser inferido a partir das características do Content-Type a ser codificado, ou, no mínimo, que certos Content-Transfer-Encodings poderia ser obrigatório para uso com tipos de conteúdo específicos. Existem várias razões pelas quais este não é o caso. Em primeiro lugar, dados os diferentes tipos de transportes utilizados para o correio, algumas codificações podem ser apropriadas para algumas combinações Content-Type / transporte e não para outras. (Por exemplo, em um transporte de 8 bits, nenhuma codificação seria necessária para o texto em determinados conjuntos de caracteres, enquanto essas codificações são claramente exigidas para SMTP de 7 bits.) Em segundo lugar, certos tipos de conteúdo podem exigir diferentes tipos de codificação de transferência em Circunstâncias diferentes. Por exemplo, muitos corpos PostScript podem consistir inteiramente de linhas curtas de dados de 7 bits e, portanto, requerem pouca ou nenhuma codificação. Outros corpos PostScript (especialmente aqueles que usam o mecanismo de codificação binária PostScripts nível 2) só podem ser razoavelmente representados usando uma codificação de transporte binário. Finalmente, uma vez que o Content-Type pretende ser um mecanismo de especificação aberto, a especificação estrita de uma associação entre Content-Types e codificações efetivamente acopla a especificação de um protocolo de aplicação com um transporte de nível inferior específico. Isso não é desejável, uma vez que os desenvolvedores de um Content-Type não devem ter conhecimento de todos os transportes em uso e quais são suas limitações. NOTA SOBRE TRANSLATING ENCODINGS As codificações quoted-printable e base64 são projetadas de modo que a conversão entre eles é possível. A única questão que surge em tal conversão é o tratamento de quebras de linha. Ao converter de quoted-printable para base64 uma quebra de linha deve ser convertida em uma seqüência CRLF. Da mesma forma, uma seqüência CRLF em dados base64 deve ser convertida em uma quebra de linha quoted-printable, mas apenas quando a conversão de dados de texto. NOTA SOBRE O MODELO DE CODIFICAÇÃO CANÓNICA: Houve alguma confusão, em versões anteriores deste memorando, com relação ao modelo para quando os dados de e-mail deveriam ser convertidos para forma canônica e codificados e, em particular, como esse processo afetaria o tratamento de CRLFs, A representação de novas linhas varia muito de sistema para sistema. Por esta razão, um modelo canônico para codificação é apresentado como Apêndice H. 5.1 Quoted Printable Content-Transfer-Encoding A codificação Quoted-Printable destina-se a representar dados que consiste em grande parte de octetos que correspondem a caracteres imprimíveis no conjunto de caracteres ASCII. Ele codifica os dados de tal forma que os octetos resultantes são improváveis de serem modificados pelo transporte de correio. Se os dados que estão sendo codificados são principalmente texto ASCII, a forma codificada dos dados permanece em grande parte reconhecível por seres humanos. Um corpo que é inteiramente ASCII também pode ser codificado em Quoted-Printable para garantir a integridade dos dados se a mensagem passar através de um caractere de tradução, e / ou line-wrapping gateway. Nessa codificação, os octetos devem ser representados conforme determinado pelas seguintes regras: Regra 1: (Representação geral de 8 bits) Qualquer octeto, exceto aqueles que indicam uma quebra de linha de acordo com a convenção de nova linha da forma canônica dos dados que estão sendo codificados, Pode ser representado por um seguido por uma representação hexadecimal de dois dígitos do valor de octetos. Os dígitos do alfabeto hexadecimal, para este fim, são 0123456789ABCDEF. Letras maiúsculas devem ser usadas ao enviar dados hexadecimais, embora uma implementação robusta possa escolher reconhecer letras minúsculas no recebimento. Assim, por exemplo, o valor 12 (ASCII form feed) pode ser representado por 0C, eo valor 61 (ASCII EQUAL SIGN) pode ser representado por 3D. Exceto quando as regras a seguir permitem uma codificação alternativa, esta regra é obrigatória. Regra 2: (Representação literal) Octetos com valores decimais de 33 a 60 inclusive, e 62 a 126, inclusive, PODEM ser representados como os caracteres ASCII que correspondem a esses octetos (EXCLAMATION POINT por LESS THAN, e GRANDE A TILDE, respectivamente ). Regra 3: (Espaço em Branco) Os Octetos com valores de 9 e 32 PODEM ser representados como caracteres ASCII TAB (HT) e SPACE, respectivamente, mas NÃO DEVEM ser assim representados no final de uma linha codificada. Todos os caracteres TAB (HT) ou espaço em uma linha codificada devem ser seguidos nessa linha por um caractere imprimível. Em particular, um no final de uma linha codificada, indicando uma quebra de linha suave (ver regra 5) pode seguir um ou mais caracteres TAB (HT) ou SPACE. Segue-se que um octeto com valor 9 ou 32 aparecendo no final de uma linha codificada deve ser representado de acordo com a Regra 1. Esta regra é necessária porque alguns MTAs (Message Transport Agents, programas que transportam mensagens de um usuário para outro ou executam Uma parte dessas transferências) são conhecidos por preencher linhas de texto com espaços, e outros são conhecidos por remover caracteres de espaço em branco a partir do final de uma linha. Portanto, ao decodificar um corpo Quoted-Printable, qualquer espaço em branco à direita em uma linha deve ser excluído, uma vez que será necessariamente adicionado por agentes de transporte intermediários. Regra 4 (Quebras de linha) Uma quebra de linha em uma parte do corpo do texto, independente do que sua representação está seguindo a representação canônica dos dados que estão sendo codificados, deve ser representada por uma quebra de linha (RFC 822), que é uma seqüência CRLF, em A codificação Quoted-Printable. Se CRs isolados e LFs, ou LF CR e CR LF seqüências são permitidos a aparecer em dados binários de acordo com a forma canônica, eles devem ser representados usando o 0D, 0A, 0A0D e 0D0A notações, respectivamente. Observe que muitas implementações podem optar por codificar a representação local de vários tipos de conteúdo diretamente. Em particular, isso pode se aplicar a texto simples em sistemas que usam convenções de nova linha, exceto delimitadores CRLF. Tal implementação é permitida, mas a geração de quebras de linha deve ser generalizada para considerar o caso em que são usadas representações alternativas de sequências de nova linha. Regra 5 (Quebras de linhas suaves) A codificação Quoted-Printable EXIGE que as linhas codificadas não tenham mais de 76 caracteres. Se as linhas mais longas devem ser codificadas com a codificação Quoted-Printable, devem ser usadas quebras de linha suaves. Um sinal de igual como o último caractere em uma linha codificada indica uma quebra de linha não significativa (macio) no texto codificado. Assim, se a forma bruta da linha é uma única linha não codificada que diz: Isso pode ser representado, na codificação Quoted-Printable, como Isso fornece um mecanismo com o qual linhas longas são codificadas de forma a ser restaurado pelo usuário agente. O limite de 76 caracteres não conta o CRLF à direita, mas conta todos os outros caracteres, incluindo quaisquer sinais iguais. Uma vez que o caractere de hífen (-) é representado como próprio na codificação Quoted-Printable, cuidado deve ser tomado, quando encapsulando um corpo codificado imprimível quoted em uma entidade multipart, para garantir que o limite de encapsulamento não aparece em qualquer lugar no corpo codificado . (Uma boa estratégia é escolher um limite que inclua uma seqüência de caracteres como o que nunca pode aparecer em um corpo de impressão entre aspas. Consulte a definição de mensagens de multipart, mais adiante neste documento.) NOTA: A codificação quoted-printable representa algo de um Compromissos entre legibilidade e fiabilidade nos transportes. Corpos codificados com a codificação quoted-printable funcionará de forma confiável sobre a maioria dos gateways de email, mas pode não funcionar perfeitamente em alguns gateways, principalmente aqueles que envolvem a tradução em EBCDIC. (Em teoria, um gateway EBCDIC poderia decodificar um corpo de impressão cotada e re-codificá-lo usando base64, mas esses gateways ainda não existem.) Um nível mais alto de confiança é oferecido pelo base64 Content-Transfer-Encoding. Uma maneira de obter um transporte razoavelmente confiável através de gateways EBCDIC é também citar os caracteres ASCII de acordo com a regra 1. Consulte o Apêndice B para obter mais informações. Uma vez que os dados de impressão com aspas são geralmente assumidos como orientados a linhas, é de se esperar que as quebras entre as linhas de dados imprimíveis cotados possam ser alteradas no transporte, da mesma forma que o correio de texto simples sempre foi alterado no correio da Internet Quando passam entre sistemas com diferentes convenções de nova linha. Se tais alterações são susceptíveis de constituir uma corrupção dos dados, é provavelmente mais sensato usar a codificação base64 em vez da codificação quoted-printable. 5.2 Base64 Content-Transfer-Encoding O Base64 Content-Transfer-Encoding é projetado para representar seqüências arbitrárias de octetos de uma forma que não seja humanamente legível. Os algoritmos de codificação e descodificação são simples, mas os dados codificados são consistentemente apenas cerca de 33 por cento maiores do que os dados não codificados. Esta codificação baseia-se na utilizada em aplicações de correio optimizado de privacidade, tal como definido na RFC 1113. A codificação base64 é adaptada do RFC 1113, com uma alteração: base64 elimina o mecanismo de texto simples incorporado. Um subconjunto de 65 caracteres de US-ASCII é usado, permitindo que 6 bits sejam representados por caractere imprimível. NOTA: Este subconjunto tem a propriedade importante de que é representado de forma idêntica em todas as versões da ISO 646, incluindo o ASCII dos EUA, e todos os caracteres no subconjunto também são representados Idêntica em todas as versões do EBCDIC. Outras codificações populares, como a codificação usada pelo utilitário UUENCODE ea codificação base85 especificada como parte do PostScript Nível 2, não compartilham essas propriedades e, portanto, não atendem aos requisitos de portabilidade que uma codificação de transporte binário para o correio deve atender. O processo de codificação representa grupos de 24 bits de bits de entrada como cadeias de saída de 4 caracteres codificados. Procedendo da esquerda para a direita, um grupo de entrada de 24 bits é formado pela concatenação de 3 grupos de entrada de 8 bits. Estes 24 bits são então tratados como 4 grupos de 6 bits concatenados, cada um dos quais é traduzido para um único dígito no alfabeto base64. Ao codificar um fluxo de bits através da codificação base64, o fluxo de bits deve ser presumido para ser encomendado com o bit de maior significância primeiro. Ou seja, o primeiro bit no fluxo será o bit de alta ordem no primeiro byte eo oitavo bit será o bit de baixa ordem no primeiro byte e assim por diante. Cada grupo de 6 bits é usado como um índice em uma matriz de 64 caracteres imprimíveis. O caractere referenciado pelo índice é colocado na string de saída. Estes caracteres, identificados na Tabela 1, são selecionados de modo a serem universalmente representáveis, e o conjunto exclui caracteres com particular significado para SMTP (por exemplo, CR, LF) e para os limites de encapsulamento definidos neste documento (por exemplo, -) . Tabela 1: O alfabeto Base64 O fluxo de saída (bytes codificados) deve ser representado em linhas de não mais de 76 caracteres cada. Todas as quebras de linha ou outros caracteres não encontrados na Tabela 1 devem ser ignorados pelo software de decodificação. Em dados base64, caracteres diferentes daqueles da Tabela 1, quebras de linha e outros espaços em branco provavelmente indicam um erro de transmissão, sobre o qual uma mensagem de aviso ou mesmo uma rejeição de mensagem pode ser apropriada em algumas circunstâncias. Processamento especial é executado se menos de 24 bits estiverem disponíveis no final dos dados que estão sendo codificados. Um quantum de codificação completo é sempre completado no final de um corpo. Quando menos de 24 bits de entrada estão disponíveis em um grupo de entrada, são adicionados bits zero (à direita) para formar um número inteiro de grupos de 6 bits. As posições de caracteres de saída que não são necessárias para representar dados de entrada reais são definidas para o caractere. Como toda a entrada de base64 é um número inteiro de octetos, somente os seguintes casos podem surgir: (1) o quantum final de entrada de codificação é um múltiplo integral de 24 bits aqui, a unidade final de saída codificada será um múltiplo integral de 4 caracteres Sem enchimento, (2) o quantum final de entrada de codificação é exatamente 8 bits aqui, a unidade final de saída codificada será dois caracteres seguidos por dois caracteres de preenchimento, ou (3) o quantum final da entrada de codificação é exatamente 16 bits aqui , A unidade final de saída codificada será três caracteres seguido por um caractere de preenchimento. Deve-se tomar cuidado para usar os octetos apropriados para quebras de linha se a codificação base64 for aplicada diretamente ao material de texto que não tenha sido convertido para a forma canônica. Em particular, as quebras de linha de texto devem ser convertidas em sequências CRLF antes da codificação base64. O importante é notar que isso pode ser feito diretamente pelo codificador em vez de em uma etapa de canonização anterior em algumas implementações. NOTA: Não há necessidade de se preocupar em cotar os limites de encapsulamento aparentes dentro de partes codificadas em base64 de entidades de várias partes, porque nenhum carácter de hífen é utilizado na codificação base64.11.1.1. Usar anotação MTOM com um serviço da Web. Com a API Java para Serviços Web Baseados em XML (JAX-WS), você pode enviar anexos binários, como imagens ou arquivos, juntamente com solicitações de serviços da Web. O JAX-WS adiciona suporte para transmissão otimizada de dados binários conforme especificado pela especificação MTOM (Message Transmission Optimization Mechanism) SOAP. O JAX-WS suporta o uso do Mecanismo Optimizado de Transmissão de Mensagens SOAP (MTOM) para enviar dados binários de anexos. Ao habilitar o MTOM, você pode enviar e receber dados binários otimamente sem incorrer no custo de codificação de dados necessário para incorporar os dados binários em um documento XML. As aplicações JAX-WS podem enviar dados binários como dados base64 ou hexBinary codificados contidos no documento XML. No entanto, para tirar proveito das otimizações fornecidas pelo MTOM, habilitar o MTOM para enviar dados binários base64 como anexos contidos fora do documento XML. A otimização do MTOM não é ativada por padrão. Aplicativos JAX-WS requerem configuração separada do cliente e os artefatos de servidor para habilitar suporte MTOM. Para o servidor, você pode ativar o MTOM em um nó de extremidade JavaBean apenas e não em nós de extremidade que implementam a interface javax. xml. ws. Provider. Desenvolva artefatos Java para seu aplicativo JAX-WS que inclua um esquema XML ou um arquivo WSDL (Web Services Description Language) que represente os dados do aplicativo de serviços da Web que incluem um anexo binário. Se você estiver começando com um arquivo WSDL, desenvolva artefatos Java a partir de um arquivo WSDL usando o comando wsimport para gerar os artefatos portáteis JAX-WS necessários. Se você estiver começando com componentes JavaBeans, desenvolva artefatos Java para aplicativos JAX-WS e, opcionalmente, gere um arquivo WSDL usando o comando wsgen. O esquema XML ou o arquivo WSDL inclui uma definição de elemento xsd: base64Binary ou xsd: hexBinary para os dados binários. Você também pode incluir o atributo xmime: expectedContentTypes no elemento para afetar o mapeamento pelo JAXB. Ativar MTOM em um nó de extremidade JavaBean. Para habilitar MTOM em um nó de extremidade, use a anotação MTOM (javax. xml. ws. soap. MTOM) no nó de extremidade. A anotação MTOM tem dois parâmetros: ativado e limiar. O parâmetro enabled tem um valor booleano e indica se MTOM está habilitado para o nó de extremidade JAX-WS. O parâmetro threshold tem um valor inteiro e especifica o tamanho mínimo para mensagens que são enviadas usando MTOM. Quando o tamanho da mensagem é menor que este inteiro especificado, a mensagem é inlined no documento XML como base64 ou hexBinary dados. Para ativar o MTOM no serviço da Web, especifique a anotação java. xml. ws. soap. MTOM na classe de implementação do nó de extremidade de serviço, conforme ilustrado no exemplo a seguir. O código relevante é mostrado em negrito: Além disso, você pode usar a anotação BindingType (javax. xml. ws. BindingType) em uma classe de implementação do nó de extremidade do servidor para especificar que o nó de extremidade suporta um dos tipos de vinculação MTOM para que as mensagens de resposta sejam MTOM - Ativado. A classe javax. xml. ws. SOAPBinding define duas constantes diferentes, SOAP11HTTPMTOMBINDING e SOAP12HTTPMTOMBINDING que você pode usar para o valor da anotação BindingType. 11.1.2. Usar diretiva MTOM em WSDL. O exemplo a seguir do WSDL demonstra o uso da afirmação da política de serialização do MIME Otimizado: As linhas (8-11) em são uma expressão de política que inclui uma afirmação de política de serialização MIME otimizada (linha 9) para indicar que o mecanismo de otimização de transmissão de mensagens SOAP (MTOM) pode ser usava. Linhas (13-18) são uma ligação WSDL. Linhas (14-16) indicam que a diretiva em Linhas (8-11) se aplica a essa vinculação, indicando especificamente que as codificações MTOM devem ser aceitas sobre todas as mensagens na vinculação. A linha (16) indica que a política é uma extensão necessária. MTOM é usado para otimizar a transmissão de mensagem SOAP sobre o fio. O MTOM usa um formato de fio de uma mensagem SOAP codificando seletivamente porções da mensagem, enquanto ainda apresenta um Infoset XML para o aplicativo SOAP. A otimização está disponível somente para o conteúdo do elemento que está em uma representação léxica canônica do tipo de dados xs: base64Binary. Parte da Mensagem: Considere uma mensagem com uma parte como base64Binary. Encadernação: mostra como a ligação usa a política MTOM: O formato de fio abaixo mostra como o envelope SOAP é transmitido usando HTTP, tome nota da parte2 que representa os dados binários e como os dados são transmitidos, observe que os dados não fazem parte Do envelope SOAP, em vez disso, ele é transmitido como uma parte MIME separada: Alguns dos pontos a serem observados no exemplo de formato de fio acima são: O anexo binário é empacotado em uma mensagem MIME em várias partes. Um elemento ltxop: Includegt é usado para marcar onde estão os dados binários. Os dados binários reais são mantidos em uma parte MIME diferente. Se os dados binários são enviados como inlined, então o tempo de execução tem que codificar os dados para xs: base64Binary. Que inchar os dados por 33, MTOM é eficiente, no sentido de que ele não tem a penalidade de aumento de tamanho de 33 que xs: base64Binary tem. É interoperável, no sentido de que é um padrão do W3C. No entanto, MIME multipart incorre um pequeno custo proporcional ao número de anexos, por isso não é adequado para um grande número de pequenos anexos. Pode-se controlar o comportamento do tempo de execução usando o limite MTOM fornecido pelo JAX-WS RI, se um anexo é menor do que o tamanho especificado no limite, ele simplesmente inline os dados binários como binário BASE64 em vez de torná-lo um anexo. 11.1.3. Usar o MTOM nos descritores de implantação Você pode ativar o MTOM no servidor usando o atributo enable-mtom no arquivo de configuração sun-jaxws. xml. Isso permite que a configuração MTOM seja alterada no momento da implantação: 11.1.4. Usar MTOMFeature com javax. xml. ws. Endpoint API javax. xml. ws. soap. MTOMFeature O MTOMFeature é usado para especificar se MTOM deve ser usado com um serviço da Web. Esse recurso deve ser usado em vez do javax. xml. ws. soap. SOAPBinding. SOAP11HTTPMTOMBINDING. Javax. xml. ws. soap. SOAPBinding. SOAP12HTTPMTOMBINDING eo javax. xml. ws. soap. SOAPBinding. setMTOMEnabled (). Este recurso DEVE ser suportado com as ligações SOAP 1.1 / HTTP ou SOAP 1.2 / HTTP. Usar esse recurso com quaisquer outras ligações é unde64257ned. Esse recurso corresponde à anotação MTOM. A ativação desse recurso no servidor ou cliente resultará no tempo de execução do JAX-WS usando o MTOM e para os dados binários sendo enviados como um anexo. O MTOMFeature tem um limite de propriedade. Que pode ser configurado para servir como uma dica para que os dados binários devem ser enviados como um anexo. O limite é o tamanho em bytes que os dados binários DEVE ser para ser enviado como um anexo. O limiar não deve ser negativo. O valor padrão é 0. 11.1.5. Use swaRef em WSDL. WS-I Attachment Profile 1.0 define o mecanismo para referenciar partes de anexos MIME usando swaRef. Neste mecanismo o conteúdo do elemento XML do tipo wsi: swaRef é enviado como anexo MIME eo elemento dentro do corpo SOAP mantém a referência a este anexo no esquema URI CID como definido pelo RFC 2111. JAXB 2.0 define o mapeamento do esquema wsi: swaRef Escreva para javax. activation. DataHandler. Um aplicativo irá construir o DataHandler com os dados eo tipo MIME apropriado e JAX-WS irá coordenar com JAXB e SAAJ para enviá-lo como anexo MIME parte. Um elemento XML do tipo wsi: swaRef é mapeado para um DataHandler e é enviado como anexo sobre o fio. Um formulário HTML é uma seção de um documento contendo conteúdo normal, marcação, elementos especiais chamados controles (caixas de seleção, botões de rádio, menus, etc.) e rótulos sobre aqueles Controles. Os usuários geralmente completam um formulário, modificando seus controles (inserindo texto, selecionando itens de menu, etc.), antes de enviar o formulário para um agente para processamento (por exemplo, para um servidor Web, para um servidor de correio, etc.) Heres um formulário simples que Inclui etiquetas, botões de opção e botões (redefinir o formulário ou enviá-lo): Nota. Esta especificação inclui informações mais detalhadas sobre formulários nas subseções sobre problemas de exibição de formulário. Um controle controle nome é dado pelo seu atributo de nome. O escopo do atributo name para um controle dentro de um elemento FORM é o elemento FORM. Cada controle tem um valor inicial e um valor atual, ambos são seqüências de caracteres. Consulte a definição de cada controle para obter informações sobre os valores iniciais e possíveis restrições sobre os valores impostos pelo controle. Em geral, um valor inicial de controles pode ser especificado com o atributo de valor de elementos de controle. No entanto, o valor inicial de um elemento TEXTAREA é dado pelo seu conteúdo eo valor inicial de um elemento OBJECT em um formulário é determinado pela implementação do objeto (ou seja, está fora do escopo desta especificação). O valor atual dos controles é primeiro ajustado para o valor inicial. Posteriormente, o valor atual dos controles pode ser modificado por interação do usuário e scripts. Um valor inicial de controles não é alterado. Thus, when a form is reset, each controls current value is reset to its initial value. If a control does not have an initial value, the effect of a form reset on that control is undefined. When a form is submitted for processing, some controls have their name paired with their current value and these pairs are submitted with the form. Those controls for which name/value pairs are submitted are called successful controls . HTML defines the following control types: buttons Authors may create three types of buttons: submit buttons. When activated, a submit button submits a form. A form may contain more than one submit button. reset buttons. When activated, a reset button resets all controls to their initial values. push buttons. Push buttons have no default behavior. Each push button may have client-side scripts associated with the elements event attributes. When an event occurs (e. g. the user presses the button, releases it, etc.), the associated script is triggered. Authors should specify the scripting language of a push button script through a default script declaration (with the META element). Authors create buttons with the BUTTON element or the INPUT element. Please consult the definitions of these elements for details about specifying different button types. Nota. Authors should note that the BUTTON element offers richer rendering capabilities than the INPUT element. checkboxes Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is on when the control elements checked attribute is set. When a form is submitted, only on checkbox controls can become successful. Several checkboxes in a form may share the same control name. Thus, for example, checkboxes allow users to select several values for the same property. The INPUT element is used to create a checkbox control. radio buttons Radio buttons are like checkboxes except that when several share the same control name. they are mutually exclusive: when one is switched on, all others with the same name are switched off. The INPUT element is used to create a radio button control. If no radio button in a set sharing the same control name is initially on, user agent behavior for choosing which control is initially on is undefined. Nota. Since existing implementations handle this case differently, the current specification differs from RFC 1866 (RFC1866 section 8.1.2.4), which states: At all times, exactly one of the radio buttons in a set is checked. If none of the ltINPUTgt elements of a set of radio buttons specifies CHECKED, then the user agent must check the first radio button of the set initially. Since user agent behavior differs, authors should ensure that in each set of radio buttons that one is initially on. menus Menus offer users options from which to choose. The SELECT element creates a menu, in combination with the OPTGROUP and OPTION elements. text input Authors may create two types of controls that allow users to input text. The INPUT element creates a single-line input control and the TEXTAREA element creates a multi-line input control. In both cases, the input text becomes the controls current value. file select This control type allows the user to select files so that their contents may be submitted with a form. The INPUT element is used to create a file select control. hidden controls Authors may create controls that are not rendered but whose values are submitted with a form. Authors generally use this control type to store information between client/server exchanges that would otherwise be lost due to the stateless nature of HTTP (see RFC2616 ). The INPUT element is used to create a hidden control. object controls Authors may insert generic objects in forms such that associated values are submitted along with other controls. Authors create object controls with the OBJECT element. The elements used to create controls generally appear inside a FORM element, but may also appear outside of a FORM element declaration when they are used to build user interfaces. This is discussed in the section on intrinsic events. Note that controls outside a form cannot be successful controls . 17.3 The FORM element action uri CT This attribute specifies a form processing agent. User agent behavior for a value other than an HTTP URI is undefined. method getpost CI This attribute specifies which HTTP method will be used to submit the form data set. Possible (case-insensitive) values are get (the default) and post. See the section on form submission for usage information. enctype content-type CI This attribute specifies the content type used to submit the form to the server (when the value of method is post). The default value for this attribute is application/x-www-form-urlencoded. The value multipart/form-data should be used in combination with the INPUT element, type file. accept-charset charset list CI This attribute specifies the list of character encodings for input data that is accepted by the server processing this form. The value is a space - and/or comma-delimited list of charset values. The client must interpret this list as an exclusive-or list, i. e. the server is able to accept any single character encoding per entity received. The default value for this attribute is the reserved string UNKNOWN. User agents may interpret this value as the character encoding that was used to transmit the document containing this FORM element. accept content-type-list CI This attribute specifies a comma-separated list of content types that a server processing this form will handle correctly. User agents may use this information to filter out non-conforming files when prompting a user to select files to be sent to the server (cf. the INPUT element when type file). name cdata CI This attribute names the element so that it may be referred to from style sheets or scripts. Nota. This attribute has been included for backwards compatibility. Applications should use the id attribute to identify elements. Attributes defined elsewhere The FORM element acts as a container for controls. It specifies: The layout of the form (given by the contents of the element). The program that will handle the completed and submitted form (the action attribute). The receiving program must be able to parse name/value pairs in order to make use of them. The method by which user data will be sent to the server (the method attribute). A character encoding that must be accepted by the server in order to handle this form (the accept-charset attribute). User agents may advise the user of the value of the accept-charset attribute and/or restrict the users ability to enter unrecognized characters. A form can contain text and markup (paragraphs, lists, etc.) in addition to form controls. The following example shows a form that is to be processed by the adduser program when submitted. The form will be sent to the program using the HTTP post method. Please consult the section on form submission for information about how user agents must prepare form data for servers and how user agents should handle expected responses. Nota. Further discussion on the behavior of servers that receive form data is beyond the scope of this specification. 17.4 The INPUT element type textpasswordcheckboxradiosubmitresetfilehiddenimagebutton CI This attribute specifies the type of control to create. The default value for this attribute is text. name cdata CI This attribute assigns the control name. value cdata CA This attribute specifies the initial value of the control. It is optional except when the type attribute has the value radio or checkbox. size cdata CN This attribute tells the user agent the initial width of the control. The width is given in pixels except when type attribute has the value text or password. In that case, its value refers to the (integer) number of characters. maxlength number CN When the type attribute has the value text or password, this attribute specifies the maximum number of characters the user may enter. This number may exceed the specified size. in which case the user agent should offer a scrolling mechanism. The default value for this attribute is an unlimited number. checked CI When the type attribute has the value radio or checkbox, this boolean attribute specifies that the button is on. User agents must ignore this attribute for other control types. src uri CT When the type attribute has the value image, this attribute specifies the location of the image to be used to decorate the graphical submit button. Attributes defined elsewhere The control type defined by the INPUT element depends on the value of the type attribute: text Creates a single-line text input control. password Like text, but the input text is rendered in such a way as to hide the characters (e. g. a series of asterisks). This control type is often used for sensitive input such as passwords. Note that the current value is the text entered by the user, not the text rendered by the user agent. Nota. Application designers should note that this mechanism affords only light security protection. Although the password is masked by user agents from casual observers, it is transmitted to the server in clear text, and may be read by anyone with low-level access to the network. checkbox Creates a checkbox. radio Creates a radio button. submit Creates a submit button. image Creates a graphical submit button. The value of the src attribute specifies the URI of the image that will decorate the button. For accessibility reasons, authors should provide alternate text for the image via the alt attribute. When a pointing device is used to click on the image, the form is submitted and the click coordinates passed to the server. The x value is measured in pixels from the left of the image, and the y value in pixels from the top of the image. The submitted data includes name. x x-value and name. y y-value where name is the value of the name attribute, and x-value and y-value are the x and y coordinate values, respectively. If the server takes different actions depending on the location clicked, users of non-graphical browsers will be disadvantaged. For this reason, authors should consider alternate approaches: Use multiple submit buttons (each with its own image) in place of a single graphical submit button. Authors may use style sheets to control the positioning of these buttons. Use a client-side image map together with scripting. reset Creates a reset button. button Creates a push button. User agents should use the value of the value attribute as the buttons label. hidden Creates a hidden control. file Creates a file select control. User agents may use the value of the value attribute as the initial file name.17.4.2 Examples of forms containing INPUT controls The following sample HTML fragment defines a simple form that allows the user to enter a first name, last name, email address, and gender. When the submit button is activated, the form will be sent to the program specified by the action attribute. This form might be rendered as follows: In the section on the LABEL element, we discuss marking up labels such as First name. In this next example, the JavaScript function name verify is triggered when the onclick event occurs: Please consult the section on intrinsic events for more information about scripting and events. The following example shows how the contents of a user-specified file may be submitted with a form. The user is prompted for his or her name and a list of file names whose contents should be submitted with the form. By specifying the enctype value of multipart/form-data, each files contents will be packaged for submission in a separate section of a multipart document. 17.5 The BUTTON element Attributes defined elsewhere Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to image, but the BUTTON element type allows content. Visual user agents may render BUTTON buttons with relief and an up/down motion when clicked, while they may render INPUT buttons as flat images. The following example expands a previous example, but creates submit and reset buttons with BUTTON instead of INPUT. The buttons contain images by way of the IMG element. Recall that authors must provide alternate text for an IMG element. It is illegal to associate an image map with an IMG that appears as the contents of a BUTTON element. ILLEGAL EXAMPLE: The following is not legal HTML. 17.6 The SELECT. OPTGROUP. and OPTION elements SELECT Attribute definitions name cdata CI This attribute assigns the control name. size number CN If a SELECT element is presented as a scrolled list box, this attribute specifies the number of rows in the list that should be visible at the same time. Visual user agents are not required to present a SELECT element as a list box they may use any other mechanism, such as a drop-down menu. multiple CI If set, this boolean attribute allows multiple selections. If not set, the SELECT element only permits single selections. Attributes defined elsewhere The SELECT element creates a menu. Each choice offered by the menu is represented by an OPTION element. A SELECT element must contain at least one OPTION element. The OPTGROUP element allows authors to group choices logically. This is particularly helpful when the user must choose from a long list of options groups of related choices are easier to grasp and remember than a single long list of options. In HTML 4, all OPTGROUP elements must be specified directly within a SELECT element (i. e. groups may not be nested). Zero or more choices may be pre-selected for the user. User agents should determine which choices are pre-selected as follows: If no OPTION element has the selected attribute set, user agent behavior for choosing which option is initially selected is undefined. Nota. Since existing implementations handle this case differently, the current specification differs from RFC 1866 (RFC1866 section 8.1.3), which states: The initial state has the first option selected, unless a SELECTED attribute is present on any of the ltOPTIONgt elements. Since user agent behavior differs, authors should ensure that each menu includes a default pre-selected OPTION . If one OPTION element has the selected attribute set, it should be pre-selected. If the SELECT element has the multiple attribute set and more than one OPTION element has the selected attribute set, they should all be pre-selected. It is considered an error if more than one OPTION element has the selected attribute set and the SELECT element does not have the multiple attribute set. User agents may vary in how they handle this error, but should not pre-select more than one choice. OPTGROUP Attribute definitions label text CS This attribute specifies the label for the option group. Attributes defined elsewhere Note. Implementors are advised that future versions of HTML may extend the grouping mechanism to allow for nested groups (i. e. OPTGROUP elements may nest). This will allow authors to represent a richer hierarchy of choices. OPTION Attribute definitions selected CI When set, this boolean attribute specifies that this option is pre-selected. value cdata CS This attribute specifies the initial value of the control. If this attribute is not set, the initial value is set to the contents of the OPTION element. label text CS This attribute allows authors to specify a shorter label for an option than the content of the OPTION element. When specified, user agents should use the value of this attribute rather than the content of the OPTION element as the option label. Attributes defined elsewhere When rendering a menu choice. user agents should use the value of the label attribute of the OPTION element as the choice. If this attribute is not specified, user agents should use the contents of the OPTION element. The label attribute of the OPTGROUP element specifies the label for a group of choices. In this example, we create a menu that allows the user to select which of seven software components to install. The first and second components are pre-selected but may be deselected by the user. The remaining components are not pre-selected. The size attribute states that the menu should only have 4 rows even though the user may select from among 7 options. The other options should be made available through a scrolling mechanism. The SELECT is followed by submit and reset buttons. Only selected options will be successful (using the control name component-select). When no options are selected, the control is not successful and neither the name nor any values are submitted to the server when the form is submitted. Note that where the value attribute is set, it determines the controls initial value. otherwise its the elements contents. In this example we use the OPTGROUP element to group choices. The following markup: represents the following grouping: Visual user agents may allow users to select from option groups through a hierarchical menu or some other mechanism that reflects the structure of choices. A graphical user agent might render this as: This image shows a SELECT element rendered as cascading menus. The top label of the menu displays the currently selected value (PortMaster 3, 3.7.1). The user has unfurled two cascading menus, but has not yet selected the new value (PortMaster 2, 3.7). Note that each cascading menu displays the label of an OPTGROUP or OPTION element. 17.7 The TEXTAREA element name cdata CI This attribute assigns the control name. rows number CN This attribute specifies the number of visible text lines. Users should be able to enter more lines than this, so user agents should provide some means to scroll through the contents of the control when the contents extend beyond the visible area. cols number CN This attribute specifies the visible width in average character widths. Users should be able to enter longer lines than this, so user agents should provide some means to scroll through the contents of the control when the contents extend beyond the visible area. User agents may wrap visible text lines to keep long lines visible without the need for scrolling. Attributes defined elsewhere The TEXTAREA element creates a multi-line text input control. User agents should use the contents of this element as the initial value of the control and should render this text initially. This example creates a TEXTAREA control that is 20 rows by 80 columns and contains two lines of text initially. The TEXTAREA is followed by submit and reset buttons. Setting the readonly attribute allows authors to display unmodifiable text in a TEXTAREA. This differs from using standard marked-up text in a document because the value of TEXTAREA is submitted with the form. 17.8 The ISINDEX element ISINDEX is deprecated . This element creates a single-line text input control. Authors should use the INPUT element to create text input controls. See the Transitional DTD for the formal definition. prompt text CS Deprecated. This attribute specifies a prompt string for the input field. Attributes defined elsewhere The ISINDEX element creates a single-line text input control that allows any number of characters. User agents may use the value of the prompt attribute as a title for the prompt. DEPRECATED EXAMPLE: The following ISINDEX declaration: could be rewritten with INPUT as follows: Semantics of ISINDEX. Currently, the semantics for ISINDEX are only well-defined when the base URI for the enclosing document is an HTTP URI. In practice, the input string is restricted to Latin-1 as there is no mechanism for the URI to specify a different character set. Some form controls automatically have labels associated with them (press buttons) while most do not (text fields, checkboxes and radio buttons, and menus). For those controls that have implicit labels, user agents should use the value of the value attribute as the label string. The LABEL element is used to specify labels for controls that do not have implicit labels, 17.9.1 The LABEL element for idref CS This attribute explicitly associates the label being defined with another control. When present, the value of this attribute must be the same as the value of the id attribute of some other control in the same document. When absent, the label being defined is associated with the elements contents. Attributes defined elsewhere The LABEL element may be used to attach information to controls. Each LABEL element is associated with exactly one form control. The for attribute associates a label with another control explicitly: the value of the for attribute must be the same as the value of the id attribute of the associated control element. More than one LABEL may be associated with the same control by creating multiple references via the for attribute. This example creates a table that is used to align two text input controls and their associated labels. Each label is associated explicitly with one text input : This example extends a previous example form to include LABEL elements. To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control. In this example, we implicitly associate two labels with two text input controls: Note that this technique cannot be used when a table is being used for layout, with the label in one cell and its associated control in another cell. When a LABEL element receives focus. it passes the focus on to its associated control. See the section below on access keys for examples. Labels may be rendered by user agents in a number of ways (e. g. visually, read by speech synthesizers, etc.) 17.10 Adding structure to forms: the FIELDSET and LEGEND elements LEGEND Attribute definitions align topbottomleftright CI Deprecated. This attribute specifies the position of the legend with respect to the fieldset. Possible values: top: The legend is at the top of the fieldset. Este é o valor padrão. bottom: The legend is at the bottom of the fieldset. left: The legend is at the left side of the fieldset. right: The legend is at the right side of the fieldset. Attributes defined elsewhere The FIELDSET element allows authors to group thematically related controls and labels. Grouping controls makes it easier for users to understand their purpose while simultaneously facilitating tabbing navigation for visual user agents and speech navigation for speech-oriented user agents. The proper use of this element makes documents more accessible. The LEGEND element allows authors to assign a caption to a FIELDSET. The legend improves accessibility when the FIELDSET is rendered non-visually. In this example, we create a form that one might fill out at the doctors office. It is divided into three sections: personal information, medical history, and current medication. Each section contains controls for inputting the appropriate information. Note that in this example, we might improve the visual presentation of the form by aligning elements within each FIELDSET (with style sheets), adding color and font information (with style sheets), adding scripting (say, to only open the current medication text area if the user indicates he or she is currently on medication), etc. In an HTML document, an element must receive focus from the user in order to become active and perform its tasks. For example, users must activate a link specified by the A element in order to follow the specified link. Similarly, users must give a TEXTAREA focus in order to enter text into it. There are several ways to give focus to an element: Designate the element with a pointing device. Navigate from one element to the next with the keyboard. The documents author may define a tabbing order that specifies the order in which elements will receive focus if the user navigates the document with the keyboard (see tabbing navigation ). Once selected, an element may be activated by some other key sequence. Select an element through an access key (sometimes called keyboard shortcut or keyboard accelerator). tabindex number CN This attribute specifies the position of the current element in the tabbing order for the current document. This value must be a number between 0 and 32767. User agents should ignore leading zeros. The tabbing order defines the order in which elements will receive focus when navigated by the user via the keyboard. The tabbing order may include elements nested within other elements. Elements that may receive focus should be navigated by user agents according to the following rules: Those elements that support the tabindex attribute and assign a positive value to it are navigated first. Navigation proceeds from the element with the lowest tabindex value to the element with the highest value. Values need not be sequential nor must they begin with any particular value. Elements that have identical tabindex values should be navigated in the order they appear in the character stream. Those elements that do not support the tabindex attribute or support it and assign it a value of 0 are navigated next. These elements are navigated in the order they appear in the character stream. Elements that are disabled do not participate in the tabbing order. In this example, the tabbing order will be the BUTTON. the INPUT elements in order (note that field1 and the button share the same tabindex, but field1 appears later in the character stream), and finally the link created by the A element. Tabbing keys. The actual key sequence that causes tabbing navigation or element activation depends on the configuration of the user agent (e. g. the tab key is used for navigation and the enter key is used to activate a selected element). User agents may also define key sequences to navigate the tabbing order in reverse. When the end (or beginning) of the tabbing order is reached, user agents may circle back to the beginning (or end). accesskey character CN This attribute assigns an access key to an element. An access key is a single character from the document character set. Nota. Authors should consider the input method of the expected reader when specifying an accesskey. Pressing an access key assigned to an element gives focus to the element. The action that occurs when an element receives focus depends on the element. For example, when a user activates a link defined by the A element, the user agent generally follows the link. When a user activates a radio button, the user agent changes the value of the radio button. When the user activates a text field, it allows input, etc. This example assigns the access key U to a label associated with an INPUT control. Typing the access key gives focus to the label which in turn gives it to the associated control. The user may then enter text into the INPUT area. In this example, we assign an access key to a link defined by the A element. Typing this access key takes the user to another document, in this case, a table of contents. The invocation of access keys depends on the underlying system. For instance, on machines running MS Windows, one generally has to press the alt key in addition to the access key. On Apple systems, one generally has to press the cmd key in addition to the access key. The rendering of access keys depends on the user agent. We recommend that authors include the access key in label text or wherever the access key is to apply. User agents should render the value of an access key in such a way as to emphasize its role and to distinguish it from other characters (e. g. by underlining it). In contexts where user input is either undesirable or irrelevant, it is important to be able to disable a control or render it read-only. For example, one may want to disable a forms submit button until the user has entered some required data. Similarly, an author may want to include a piece of read-only text that must be submitted as a value along with the form. The following sections describe disabled and read-only controls. disabled CI When set for a form control, this boolean attribute disables the control for user input. When set, the disabled attribute has the following effects on an element: This attribute is inherited but local declarations override the inherited value. How disabled elements are rendered depends on the user agent. For example, some user agents gray out disabled menu items, button labels, etc. In this example, the INPUT element is disabled. Therefore, it cannot receive user input nor will its value be submitted with the form. Nota. The only way to modify dynamically the value of the disabled attribute is through a script. readonly CI When set for a form control, this boolean attribute prohibits changes to the control. The readonly attribute specifies whether the control may be modified by the user. When set, the readonly attribute has the following effects on an element: Read-only elements receive focus but cannot be modified by the user. Read-only elements are included in tabbing navigation . Read-only elements may be successful . The following elements support the readonly attribute: INPUT and TEXTAREA . How read-only elements are rendered depends on the user agent. Nota. The only way to modify dynamically the value of the readonly attribute is through a script. The following sections explain how user agents submit form data to form processing agents. The method attribute of the FORM element specifies the HTTP method used to send the form to the processing agent. This attribute may take two values: get: With the HTTP get method, the form data set is appended to the URI specified by the action attribute (with a question-mark () as separator) and this new URI is sent to the processing agent. post: With the HTTP post method, the form data set is included in the body of the form and sent to the processing agent. The get method should be used when the form is idempotent (i. e. causes no side-effects). Many database searches have no visible side-effects and make ideal applications for the get method. If the service associated with the processing of a form causes side effects (for example, if the form modifies a database or subscription to a service), the post method should be used. Nota. The get method restricts form data set values to ASCII characters. Only the post method (with enctype multipart/form-data) is specified to cover the entire ISO10646 character set. A successful control is valid for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name. Controls that are disabled cannot be successful. If a form contains more than one submit button. only the activated submit button is successful. All on checkboxes may be successful. For radio buttons that share the same value of the name attribute, only the on radio button may be successful. For menus. the control name is provided by a SELECT element and values are provided by OPTION elements. Only selected options may be successful. When no options are selected, the control is not successful and neither the name nor any values are submitted to the server when the form is submitted. The current value of a file select is a list of one or more file names. Upon submission of the form, the contents of each file are submitted with the rest of the form data. The file contents are packaged according to the forms content type . The current value of an object control is determined by the objects implementation. If a control doesnt have a current value when the form is submitted, user agents are not required to treat it as a successful control. Furthermore, user agents should not consider the following controls successful: Hidden controls and controls that are not rendered because of style sheet settings may still be successful. For example: will still cause a value to be paired with the name invisible-password and submitted with the form. When the user submits a form (e. g. by activating a submit button ), the user agent processes it as follows. Step one: Identify the successful controls Step two: Build a form data set The form data set is then encoded according to the content type specified by the enctype attribute of the FORM element. Finally, the encoded data is sent to the processing agent designated by the action attribute using the protocol specified by the method attribute. This specification does not specify all valid submission methods or content types that may be used with forms. However, HTML 4 user agents must support the established conventions in the following cases: If the method is get and the action is an HTTP URI, the user agent takes the value of action. appends a to it, then appends the form data set. encoded using the application/x-www-form-urlencoded content type. The user agent then traverses the link to this URI. In this scenario, form data are restricted to ASCII codes. If the method is post and the action is an HTTP URI, the user agent conducts an HTTP post transaction using the value of the action attribute and a message created according to the content type specified by the enctype attribute. For any other value of action or method. behavior is unspecified. User agents should render the response from the HTTP get and post transactions. The enctype attribute of the FORM element specifies the content type used to encode the form data set for submission to the server. User agents must support the content types listed below. Behavior for other content types is unspecified. This is the default content type. Forms submitted with this content type must be encoded as follows: Control names and values are escaped. Space characters are replaced by . and then reserved characters are escaped as described in RFC1738. section 2.2: Non-alphanumeric characters are replaced by HH. a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as CR LF pairs (i. e. 0D0A ). The control names/values are listed in the order they appear in the document. The name is separated from the value by and name/value pairs are separated from each other by amp . Nota. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between multipart/form-data and other content types, performance issues, etc. Please consult the appendix for information about security issues for forms . The content type application/x-www-form-urlencoded is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type multipart/form-data should be used for submitting forms that contain files, non-ASCII data, and binary data. The content multipart/form-data follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of multipart/form-data is available at the IANA registry. A multipart/form-data message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data how this is done lies outside the scope of this specification. As with all multipart MIME types, each part has an optional Content-Type header that defaults to text/plain. User agents should supply the Content-Type header, accompanied by a charset parameter. Each part is expected to contain: a Content-Disposition header whose value is form-data. a name attribute specifying the control name of the corresponding control. Control names originally encoded in non-ASCII character sets may be encoded using the method outlined in RFC2045 . Thus, for example, for a control named mycontrol, the corresponding part would be specified: As with all MIME transmissions, CR LF (i. e. 0D0A ) is used to separate lines of data. Each part may be encoded and the Content-Transfer-Encoding header supplied if the value of that part does not conform to the default (7BIT) encoding (see RFC2045. section 6) If the contents of a file are submitted with a form, the file input should be identified by the appropriate content type (e. g. application/octet-stream). If multiple files are to be returned as the result of a single form entry, they should be returned as multipart/mixed embedded within the multipart/form-data. The user agent should attempt to supply a file name for each submitted file. The file name may be specified with the filename parameter of the Content-Disposition: form-data header, or, in the case of multiple files, in a Content-Disposition: file header of the subpart. If the file name of the clients operating system is not in US-ASCII, the file name might be approximated or encoded using the method of RFC2045. This is convenient for those cases where, for example, the uploaded files might contain references to each other (e. g. a TeX file and its. sty auxiliary style description). The following example illustrates multipart/form-data encoding. Suppose we have the following form: If the user enters Larry in the text input, and selects the text file file1.txt, the user agent might send back the following data: If the user selected a second (image) file file2.gif, the user agent might construct the parts as follows:
No comments:
Post a Comment