WebClient.UploadFile Método

Definição

Faz upload de um arquivo local para um recurso com o URI especificado.Uploads a local file to a resource with the specified URI.

Sobrecargas

UploadFile(String, String)

Carrega o arquivo local especificado para u recurso com o URI especificado.Uploads the specified local file to a resource with the specified URI.

UploadFile(Uri, String)

Carrega o arquivo local especificado para u recurso com o URI especificado.Uploads the specified local file to a resource with the specified URI.

UploadFile(String, String, String)

Carrega o arquivo local especificado no recurso especificado, usando o método especificado.Uploads the specified local file to the specified resource, using the specified method.

UploadFile(Uri, String, String)

Carrega o arquivo local especificado no recurso especificado, usando o método especificado.Uploads the specified local file to the specified resource, using the specified method.

UploadFile(String, String)

Carrega o arquivo local especificado para u recurso com o URI especificado.Uploads the specified local file to a resource with the specified URI.

public:
 cli::array <System::Byte> ^ UploadFile(System::String ^ address, System::String ^ fileName);
public byte[] UploadFile (string address, string fileName);
member this.UploadFile : string * string -> byte[]
Public Function UploadFile (address As String, fileName As String) As Byte()

Parâmetros

address
String

O URI do recurso que receberá o arquivo.The URI of the resource to receive the file. Por exemplo, ftp://localhost/samplefile.txt.For example, ftp://localhost/samplefile.txt.

fileName
String

O arquivo a ser enviado para o recurso.The file to send to the resource. Por exemplo, "samplefile.txt".For example, "samplefile.txt".

Retornos

Byte[]

Uma matriz Byte que contém o corpo da resposta do recurso.A Byte array containing the body of the response from the resource.

Exceções

O parâmetro address é null.The address parameter is null.

- ou --or-

O parâmetro fileName é null.The fileName parameter is null.

O URI formado pela combinação de BaseAddress e address é inválido.The URI formed by combining BaseAddress, and address is invalid.

- ou --or-

fileName é null, é Empty, contém caracteres inválidos ou não existe.fileName is null, is Empty, contains invalid characters, or does not exist.

- ou --or-

Ocorreu um erro ao carregar o arquivo.An error occurred while uploading the file.

- ou --or-

Não houve resposta do servidor que hospeda o recurso.There was no response from the server hosting the resource.

- ou --or-

O cabeçalho Content-type começa com multipart.The Content-type header begins with multipart.

Exemplos

O exemplo de código a seguir carrega o arquivo especificado para o URI especificado usando UploadFile .The following code example uploads the specified file to the specified URI using UploadFile. Qualquer resposta retornada pelo servidor é exibida no console do.Any response returned by the server is displayed on the console.

Console::Write( "\nPlease enter the URI to post data to : " );
String^ uriString = Console::ReadLine();

// Create a new WebClient instance.
WebClient^ myWebClient = gcnew WebClient;
Console::WriteLine( "\nPlease enter the fully qualified path of the file to be uploaded to the URI" );
String^ fileName = Console::ReadLine();
Console::WriteLine( "Uploading {0} to {1} ...", fileName, uriString );

// Upload the file to the URI.
// The 'UploadFile(uriString, fileName)' method implicitly uses HTTP POST method.
array<Byte>^responseArray = myWebClient->UploadFile( uriString, fileName );

// Decode and display the response.
Console::WriteLine( "\nResponse Received::The contents of the file uploaded are: \n {0}", 
    System::Text::Encoding::ASCII->GetString( responseArray ) );
Console.Write("\nPlease enter the URI to post data to : ");
String uriString = Console.ReadLine();

// Create a new WebClient instance.
WebClient myWebClient = new WebClient();

Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URI");
string fileName = Console.ReadLine();
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);

// Upload the file to the URI.
// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

// Decode and display the response.
Console.WriteLine("\nResponse Received. The contents of the file uploaded are:\n{0}", 
    System.Text.Encoding.ASCII.GetString(responseArray));

Console.Write(ControlChars.Cr + "Please enter the URI to post data to : ")
Dim uriString As String = Console.ReadLine()

' Create a new WebClient instance.
Dim myWebClient As New WebClient()

Console.WriteLine(ControlChars.Cr & _
    "Please enter the fully qualified path of the file to be uploaded to the URI")

Dim fileName As String = Console.ReadLine()
Console.WriteLine("Uploading {0} to {1} ...", fileName, uriString)

' Upload the file to the URI.
' The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method. 
Dim responseArray As Byte() = myWebClient.UploadFile(uriString, fileName)

' Decode and display the response.
Console.WriteLine(ControlChars.Cr & "Response Received. The contents of the file uploaded are: " & _
    ControlChars.Cr & "{0}", System.Text.Encoding.ASCII.GetString(responseArray))

O exemplo de código a seguir mostra uma página ASP.NET que pode aceitar arquivos postados e é adequada para uso com o UploadFile método.The following code example shows an ASP.NET page that can accept posted files and is suitable for use with the UploadFile method. A página deve residir em um servidor Web.The page must reside on a Web server. Seu endereço fornece o valor para o address parâmetro do UploadFile método.Its address provides the value for the address parameter of the UploadFile method.

<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {
    
    foreach(string f in Request.Files.AllKeys) {
        HttpPostedFile file = Request.Files[f];
        file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
    }	
}

</Script>
<html>
<body>
<p> Upload complete.  </p>
</body>
</html>
<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="VB" runat=server>
    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
        Dim f As String
        Dim file
        For Each f In Request.Files.AllKeys
            file = Request.Files(f)
            file.SaveAs("c:\inetpub\test\UploadedFiles\" & file.FileName)
        Next f
        
    End Sub

</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>

Comentários

O UploadFile método envia um arquivo local para um recurso.The UploadFile method sends a local file to a resource. Esse método usa o comando arma para carregar um recurso de FTP.This method uses the STOR command to upload an FTP resource. Para um recurso HTTP, o método POST é usado.For an HTTP resource, the POST method is used.

Esse método é bloqueado durante o carregamento do arquivo.This method blocks while uploading the file. Para continuar a execução enquanto aguarda a resposta do servidor, use um dos UploadFileAsync métodos.To continue executing while waiting for the server's response, use one of the UploadFileAsync methods.

O POST método é definido por http.The POST method is defined by HTTP. Se a solicitação subjacente não usar HTTP e POST não for compreendida pelo servidor, as classes de protocolo subjacentes determinarão o que ocorre.If the underlying request does not use HTTP and POST is not understood by the server, the underlying protocol classes determine what occurs. Normalmente, um WebException é lançado com a Status propriedade definida para indicar o erro.Typically, a WebException is thrown with the Status property set to indicate the error.

Se a BaseAddress propriedade não for uma cadeia de caracteres vazia ("") e não address contiver um URI absoluto, address deverá ser um URI relativo que é combinado com BaseAddress para formar o URI absoluto dos dados solicitados.If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. Se a QueryString propriedade não for uma cadeia de caracteres vazia, ela será anexada address .If the QueryString property is not an empty string, it is appended to address.

Observação

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede em .NET Framework.For more information, see Network Tracing in .NET Framework.

Aplica-se a

UploadFile(Uri, String)

Carrega o arquivo local especificado para u recurso com o URI especificado.Uploads the specified local file to a resource with the specified URI.

public:
 cli::array <System::Byte> ^ UploadFile(Uri ^ address, System::String ^ fileName);
public byte[] UploadFile (Uri address, string fileName);
member this.UploadFile : Uri * string -> byte[]
Public Function UploadFile (address As Uri, fileName As String) As Byte()

Parâmetros

address
Uri

O URI do recurso que receberá o arquivo.The URI of the resource to receive the file. Por exemplo, ftp://localhost/samplefile.txt.For example, ftp://localhost/samplefile.txt.

fileName
String

O arquivo a ser enviado para o recurso.The file to send to the resource. Por exemplo, "samplefile.txt".For example, "samplefile.txt".

Retornos

Byte[]

Uma matriz Byte que contém o corpo da resposta do recurso.A Byte array containing the body of the response from the resource.

Exceções

O parâmetro address é null.The address parameter is null.

- ou --or-

O parâmetro fileName é null.The fileName parameter is null.

O URI formado pela combinação de BaseAddress e address é inválido.The URI formed by combining BaseAddress, and address is invalid.

- ou --or-

fileName é null, é Empty, contém caracteres inválidos ou não existe.fileName is null, is Empty, contains invalid characters, or does not exist.

- ou --or-

Ocorreu um erro ao carregar o arquivo.An error occurred while uploading the file.

- ou --or-

Não houve resposta do servidor que hospeda o recurso.There was no response from the server hosting the resource.

- ou --or-

O cabeçalho Content-type começa com multipart.The Content-type header begins with multipart.

Comentários

O UploadFile método envia um arquivo local para um recurso.The UploadFile method sends a local file to a resource. Esse método usa o comando arma para carregar um recurso de FTP.This method uses the STOR command to upload an FTP resource. Para um recurso HTTP, o método POST é usado.For an HTTP resource, the POST method is used.

Esse método é bloqueado durante o carregamento do arquivo.This method blocks while uploading the file. Para continuar a execução enquanto aguarda a resposta do servidor, use um dos UploadFileAsync métodos.To continue executing while waiting for the server's response, use one of the UploadFileAsync methods.

O POST método é definido por http.The POST method is defined by HTTP. Se a solicitação subjacente não usar HTTP e POST não for compreendida pelo servidor, as classes de protocolo subjacentes determinarão o que ocorre.If the underlying request does not use HTTP and POST is not understood by the server, the underlying protocol classes determine what occurs. Normalmente, um WebException é lançado com a Status propriedade definida para indicar o erro.Typically, a WebException is thrown with the Status property set to indicate the error.

Se a BaseAddress propriedade não for uma cadeia de caracteres vazia ("") e não address contiver um URI absoluto, address deverá ser um URI relativo que é combinado com BaseAddress para formar o URI absoluto dos dados solicitados.If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. Se a QueryString propriedade não for uma cadeia de caracteres vazia, ela será anexada address .If the QueryString property is not an empty string, it is appended to address.

Observação

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede em .NET Framework.For more information, see Network Tracing in .NET Framework.

Aplica-se a

UploadFile(String, String, String)

Carrega o arquivo local especificado no recurso especificado, usando o método especificado.Uploads the specified local file to the specified resource, using the specified method.

public:
 cli::array <System::Byte> ^ UploadFile(System::String ^ address, System::String ^ method, System::String ^ fileName);
public byte[] UploadFile (string address, string? method, string fileName);
public byte[] UploadFile (string address, string method, string fileName);
member this.UploadFile : string * string * string -> byte[]
Public Function UploadFile (address As String, method As String, fileName As String) As Byte()

Parâmetros

address
String

O URI do recurso que receberá o arquivo.The URI of the resource to receive the file.

method
String

O método usado para enviar o arquivo para o recurso.The method used to send the file to the resource. Se for null, o padrão será POST para http e STOR para ftp.If null, the default is POST for http and STOR for ftp.

fileName
String

O arquivo a ser enviado para o recurso.The file to send to the resource.

Retornos

Byte[]

Uma matriz Byte que contém o corpo da resposta do recurso.A Byte array containing the body of the response from the resource.

Exceções

O parâmetro address é null.The address parameter is null.

- ou --or-

O parâmetro fileName é null.The fileName parameter is null.

O URI formado pela combinação de BaseAddress e address é inválido.The URI formed by combining BaseAddress, and address is invalid.

- ou --or-

fileName é null, é Empty, contém caracteres inválidos ou não existe.fileName is null, is Empty, contains invalid characters, or does not exist.

- ou --or-

Ocorreu um erro ao carregar o arquivo.An error occurred while uploading the file.

- ou --or-

Não houve resposta do servidor que hospeda o recurso.There was no response from the server hosting the resource.

- ou --or-

O cabeçalho Content-type começa com multipart.The Content-type header begins with multipart.

Exemplos

O exemplo de código a seguir carrega o arquivo especificado para o URI especificado usando UploadFile .The following code example uploads the specified file to the specified URI using UploadFile. Qualquer resposta retornada pelo servidor é exibida no console do.Any response returned by the server is displayed on the console.

Console::Write( "\nPlease enter the URL to post data to : " );
String^ uriString = Console::ReadLine();

// Create a new WebClient instance.
WebClient^ myWebClient = gcnew WebClient;
Console::WriteLine
    ("\nPlease enter the fully qualified path of the file to be uploaded to the URL" );
String^ fileName = Console::ReadLine();
Console::WriteLine( "Uploading {0} to {1} ...", fileName, uriString );

// Upload the file to the URL using the HTTP 1.0 POST.
array<Byte>^responseArray = myWebClient->UploadFile( uriString, "POST", fileName );

// Decode and display the response.
Console::WriteLine( "\nResponse Received::The contents of the file uploaded are: \n {0}", 
    System::Text::Encoding::ASCII->GetString( responseArray ));
Console.Write("\nPlease enter the URL to post data to : ");
String uriString = Console.ReadLine();

// Create a new WebClient instance.
WebClient myWebClient = new WebClient();

Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URL");
string fileName = Console.ReadLine();

Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);						
// Upload the file to the URL using the HTTP 1.0 POST.
byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);

// Decode and display the response.
Console.WriteLine("\nResponse Received. The contents of the file uploaded are:\n{0}",
    System.Text.Encoding.ASCII.GetString(responseArray));


Console.Write(ControlChars.Cr + "Please enter the URL to post data to : ")
Dim uriString As String = Console.ReadLine()

' Create a new WebClient instance.
Dim myWebClient As New WebClient()
Console.WriteLine(ControlChars.Cr & _
    "Please enter the fully qualified path of the file to be uploaded to the URL")

Dim fileName As String = Console.ReadLine()
Console.WriteLine("Uploading {0} to {1} ...", fileName, uriString)

' Upload the file to the Url using the HTTP 1.0 POST.
Dim responseArray As Byte() = myWebClient.UploadFile(uriString, "POST", fileName)

' Decode and display the response.
Console.WriteLine(ControlChars.Cr + "Response Received. The contents of the file uploaded are: " & _
    ControlChars.Cr & "{0}", System.Text.Encoding.ASCII.GetString(responseArray))

O exemplo de código a seguir mostra uma página ASP.NET que pode aceitar arquivos postados e é adequada para uso com o UploadFile método.The following code example shows an ASP.NET page that can accept posted files and is suitable for use with the UploadFile method. A página deve residir em um servidor Web.The page must reside on a Web server. Seu endereço fornece o valor para o address parâmetro do UploadFile método.Its address provides the value for the address parameter of the UploadFile method.

<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>
void Page_Load(object sender, EventArgs e) {
    
    foreach(string f in Request.Files.AllKeys) {
        HttpPostedFile file = Request.Files[f];
        file.SaveAs("c:\\inetpub\\test\\UploadedFiles\\" + file.FileName);
    }	
}

</Script>
<html>
<body>
<p> Upload complete.  </p>
</body>
</html>
<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="VB" runat=server>
    Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        
        Dim f As String
        Dim file
        For Each f In Request.Files.AllKeys
            file = Request.Files(f)
            file.SaveAs("c:\inetpub\test\UploadedFiles\" & file.FileName)
        Next f
        
    End Sub

</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>

Comentários

Quando o endereço especifica um recurso HTTP, o UploadFile método envia um arquivo local para um recurso usando o método HTTP especificado no method parâmetro e retorna qualquer resposta do servidor.When address specifies an HTTP resource, the UploadFile method sends a local file to a resource using the HTTP method specified in the method parameter and returns any response from the server. Esse método é bloqueado durante o carregamento do arquivo.This method blocks while uploading the file. Para continuar a execução enquanto aguarda a resposta do servidor, use um dos UploadFileAsync métodos.To continue executing while waiting for the server's response, use one of the UploadFileAsync methods.

Se o method parâmetro especificar um verbo que não é compreendido pelo servidor ou pelo address recurso, as classes de protocolo subjacentes determinarão o que ocorre.If the method parameter specifies a verb that is not understood by the server or the address resource, the underlying protocol classes determine what occurs. Normalmente, um WebException é lançado com a Status propriedade definida para indicar o erro.Typically, a WebException is thrown with the Status property set to indicate the error.

Se a BaseAddress propriedade não for uma cadeia de caracteres vazia ("") e não address contiver um URI absoluto, address deverá ser um URI relativo que é combinado com BaseAddress para formar o URI absoluto dos dados solicitados.If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. Se a QueryString propriedade não for uma cadeia de caracteres vazia, ela será anexada address .If the QueryString property is not an empty string, it is appended to address.

Observação

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede em .NET Framework.For more information, see Network Tracing in .NET Framework.

Aplica-se a

UploadFile(Uri, String, String)

Carrega o arquivo local especificado no recurso especificado, usando o método especificado.Uploads the specified local file to the specified resource, using the specified method.

public:
 cli::array <System::Byte> ^ UploadFile(Uri ^ address, System::String ^ method, System::String ^ fileName);
public byte[] UploadFile (Uri address, string? method, string fileName);
public byte[] UploadFile (Uri address, string method, string fileName);
member this.UploadFile : Uri * string * string -> byte[]
Public Function UploadFile (address As Uri, method As String, fileName As String) As Byte()

Parâmetros

address
Uri

O URI do recurso que receberá o arquivo.The URI of the resource to receive the file.

method
String

O método usado para enviar o arquivo para o recurso.The method used to send the file to the resource. Se for null, o padrão será POST para http e STOR para ftp.If null, the default is POST for http and STOR for ftp.

fileName
String

O arquivo a ser enviado para o recurso.The file to send to the resource.

Retornos

Byte[]

Uma matriz Byte que contém o corpo da resposta do recurso.A Byte array containing the body of the response from the resource.

Exceções

O parâmetro address é null.The address parameter is null.

- ou --or-

O parâmetro fileName é null.The fileName parameter is null.

O URI formado pela combinação de BaseAddress e address é inválido.The URI formed by combining BaseAddress, and address is invalid.

- ou --or-

fileName é null, é Empty, contém caracteres inválidos ou não existe.fileName is null, is Empty, contains invalid characters, or does not exist.

- ou --or-

Ocorreu um erro ao carregar o arquivo.An error occurred while uploading the file.

- ou --or-

Não houve resposta do servidor que hospeda o recurso.There was no response from the server hosting the resource.

- ou --or-

O cabeçalho Content-type começa com multipart.The Content-type header begins with multipart.

Comentários

Quando o endereço especifica um recurso HTTP, o UploadFile método envia um arquivo local para um recurso usando o método HTTP especificado no method parâmetro e retorna qualquer resposta do servidor.When address specifies an HTTP resource, the UploadFile method sends a local file to a resource using the HTTP method specified in the method parameter and returns any response from the server. Esse método é bloqueado durante o carregamento do arquivo.This method blocks while uploading the file. Para continuar a execução enquanto aguarda a resposta do servidor, use um dos UploadFileAsync métodos.To continue executing while waiting for the server's response, use one of the UploadFileAsync methods.

Se o method parâmetro especificar um verbo que não é compreendido pelo servidor ou pelo address recurso, as classes de protocolo subjacentes determinarão o que ocorre.If the method parameter specifies a verb that is not understood by the server or the address resource, the underlying protocol classes determine what occurs. Normalmente, um WebException é lançado com a Status propriedade definida para indicar o erro.Typically, a WebException is thrown with the Status property set to indicate the error.

Se a BaseAddress propriedade não for uma cadeia de caracteres vazia ("") e não address contiver um URI absoluto, address deverá ser um URI relativo que é combinado com BaseAddress para formar o URI absoluto dos dados solicitados.If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. Se a QueryString propriedade não for uma cadeia de caracteres vazia, ela será anexada address .If the QueryString property is not an empty string, it is appended to address.

Observação

Esse membro emite o rastreamento de informações quando você ativa o rastreamento de rede em seu aplicativo.This member outputs trace information when you enable network tracing in your application. Para obter mais informações, consulte rastreamento de rede em .NET Framework.For more information, see Network Tracing in .NET Framework.

Aplica-se a